Re: Puzzle: Add One Without Using + OR -

From: Alf P. Steinbach (alfps_at_start.no)
Date: 09/20/04


Date: Mon, 20 Sep 2004 21:47:54 GMT


* Method Man:
> Q:
> Write a C/C++ program that takes an unsigned integer and adds 1 to it
> without using the plus or minus signs. Don't worry about overflow issues. It
> is cheating to use assembly commands, or to write a preprocessor that uses
> ASCII codes to insert the plus or minus sign. There are many solutions, some
> more elegant than others.
>
> Here's the solution I came up with. I'm wondering if there's a solution that
> is more elegant or efficient.
>
>
> void addOne(unsigned int &i) {
> int j = 1;
>
> while (i & 1) {
> i >>= 1;
> j <<= 1;
> }
> i |= 1;
>
> while !(j & 1) {
> i <<= 1;
> j >>= 1;
> }
> }

Good attempt, but regarding style, preferentially use a function rather than
an in/out argument, and regarding C++, the above shouldn't compile: always
post code that compiles (except when the point is that it doesn't compile).

At the risk of doing your HOMEWORK for you:

    unsigned next( unsigned x )
    {
        if( x == ~0 ) { return 0; }
        unsigned flipmask = ~0;
        while( (x | flipmask) == ~0 )
        {
            flipmask <<= 1;
        }
        return x ^ ~flipmask;
    }

State the assumptions that this solution relies on.

-- 
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?


Relevant Pages

  • Re: WDK KMDF 1.0 does not build nmake error U1065
    ... Compile and Link for i386 ... minus sign, you get something that looks like a minus sign, but ... Now even after you make that adjustment, some WDK samples still don't ... Well they do if you figure out what ANSI code page Microsoft ...
    (microsoft.public.development.device.drivers)
  • Re: 11
    ... >> Needless to say that ^A is a basis for clean definition of minus ... > "A proof is elegant if you wish you'd thought of it." ... > with outer union. ...
    (comp.databases.theory)
  • Re: WDK KMDF 1.0 does not build nmake error U1065
    ... Compile and Link for i386 ... minus sign, you get something that looks like a minus sign, but Microsoft's ... Now even after you make that adjustment, some WDK samples still don't ... Well they do if you figure out what ANSI code page Microsoft ...
    (microsoft.public.development.device.drivers)
  • Puzzle: Add One Without Using + OR -
    ... Don't worry about overflow issues. ... ASCII codes to insert the plus or minus sign. ... is more elegant or efficient. ... void addOne(unsigned int &i) { ...
    (comp.lang.cpp)
  • lcc-win32 conformance question
    ... If I compile this program ... return 0; // foo bar baz ... (minus the quotes), no diagnostic is produced; ...
    (comp.lang.c)

Loading