Re: Puzzle: Add One Without Using + OR -
From: Alf P. Steinbach (alfps_at_start.no)
Date: 09/20/04
- Next message: Andre Kostur: "Re: How stupid can a compiler be?!"
- Previous message: JKop: "How stupid can a compiler be?!"
- In reply to: Method Man: "Puzzle: Add One Without Using + OR -"
- Next in thread: Method Man: "Re: Puzzle: Add One Without Using + OR -"
- Reply: Method Man: "Re: Puzzle: Add One Without Using + OR -"
- Reply: Method Man: "Re: Puzzle: Add One Without Using + OR -"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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?
- Next message: Andre Kostur: "Re: How stupid can a compiler be?!"
- Previous message: JKop: "How stupid can a compiler be?!"
- In reply to: Method Man: "Puzzle: Add One Without Using + OR -"
- Next in thread: Method Man: "Re: Puzzle: Add One Without Using + OR -"
- Reply: Method Man: "Re: Puzzle: Add One Without Using + OR -"
- Reply: Method Man: "Re: Puzzle: Add One Without Using + OR -"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|