473,386 Members | 1,726 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Puzzle: Add One Without Using + OR -

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;
}
}
Jul 22 '05 #1
25 2195

"Method Man" <a@b.c> wrote in message news:Bt************@read1.cgocable.net...
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 a funny one.

#include <vector>

void addOne(unsigned int &i) {
std::vector<char> v(i);
v.push_back('q');
i = (unsigned int) v.size();
}

Jonathan
Jul 22 '05 #2
* 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?
Jul 22 '05 #3
In article <Bt************@read1.cgocable.net>, Method Man <a@b.c> wrote:
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's actually easier to treat unsigned overflow the same way the ++
operator does it, by wrapping around, than by treating it as a "Don't
worry about this" special case.)

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;
}
}

I have a solution that only uses one loop:
--------
/*Exercises for the reader:
-Find and correct the deliberately introduced bug
(that is, don't hand this in as your homework without thinking about it
first, or you'll fail)
-Explain what effect the bug has and why
-Reconstruct my comments explaining what the code is doing and why
*/
unsigned long inc(unsigned long i)
{
unsigned long j=1;
while(j)
{
i^=j;
if(!(i&j))
return i;
j<<=1;
}
return i;
}
--------
dave

--
Dave Vandervies dj******@csclub.uwaterloo.ca Just like C, vi is not incompetent-friendly.

I disagree. I get on just fine with both C and vi.
--Dan Pop and Richard Heathfield in comp.lang.c
Jul 22 '05 #4

"Alf P. Steinbach" <al***@start.no> wrote in message
news:41****************@news.individual.net...
* 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).
Oops, I hand wrote my code without compiling.
At the risk of doing your HOMEWORK for you:

Not homework, just an interesting puzzle I found.
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.


That's clever. I didn't think of using ~0.
I beleive the assumption is that on overflow, the value will roll back to 0.
Jul 22 '05 #5

"Alf P. Steinbach" <al***@start.no> wrote in message
news:41****************@news.individual.net...
* 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).
Oops. I just posted code that I wrote on a peice of paper without compiling
it.
At the risk of doing your HOMEWORK for you:
Not homework, just an interesting puzzle I came across on the web.

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.


That's clever. I didn't think of using ~0.
I beleive the assumption is that when an overflow occurs, the value should
roll back to 0.
Jul 22 '05 #6

"Method Man" <a@b.c> wrote in message news:Bt************@read1.cgocable.net...
Q:
void addOne(unsigned int &i) {
int j = 1;

while (i & 1) {
i >>= 1;
j <<= 1;
}
i |= 1;

while !(j & 1) {
i <<= 1;
j >>= 1;


unsigned int bit = 1;
// While we are looking at bits that have value 1, we clear the
// value and shift left to carry the one to the next place.
//
while(i & bit) {
i &= ~bit; // add one
bit <<= 1; // carry;
}
//
// When we get here, the bit is zero, so we can add just by oring 1 to this position.
i |= bit; // don't need to carry (was zero)

Jul 22 '05 #7
Jonathan wrote:
Method Man wrote:
Q:
Write a C/C++ program that takes an unsigned integer and adds 1 to it
without using the plus or minus signs.
....
Here's a funny one.

#include <vector>

void addOne(unsigned int &i) {
std::vector<char> v(i);
v.push_back('q');
i = (unsigned int) v.size();
}


Very cute !

How about:

#include <unistd.h>
#include <ctime>

unsigned int addOne(unsigned int i)
{
time_t t = (time_t) i;
stime(&t); // set the current time
sleep(1);
return time(0);
}

There may be unfortunate side effects, though ... and it may not be all that
portable ... and it might not work sometimes ... but apart from that ... :-)

David Fisher
Sydney, Australia
Jul 22 '05 #8
I am curious to know if the gurus think that this kind of question has any use
beyond impressing girls at cocktail parties.

Would you actually deny somebody a C++ job if they couldn't answer this
question?

I ask because I consider myself to be an effective C++ developer but I
generally don't do well with this type of question or at the very least I feel
I have to put more thought into it than I think should be necessary.
Jul 22 '05 #9
"Method Man" <a@b.c> wrote in message news:<Bt************@read1.cgocable.net>...
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 mine:

unsigned int increment(unsigned int number) {
unsigned int mask = 1;

for (; mask & number; mask <<= 1)
number ^= mask;

return number | mask;
}

From the least-significant-bit up, turn 1's into 0's until you hit a
zero. Turn that one into a one.

Jusitn Dubs
Jul 22 '05 #10

"Justin Dubs" <jt****@eos.ncsu.edu> wrote in message
news:2e**************************@posting.google.c om...
"Method Man" <a@b.c> wrote in message

news:<Bt************@read1.cgocable.net>...
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 mine:

unsigned int increment(unsigned int number) {
unsigned int mask = 1;

for (; mask & number; mask <<= 1)
number ^= mask;

return number | mask;
}

From the least-significant-bit up, turn 1's into 0's until you hit a
zero. Turn that one into a one.

Jusitn Dubs


As an aside, is the | operator more efficient than the ^ operator? I would
imagine it is best to try using primitive gates whenever possible. (Then
again, internally everything could just be NAND gates).
Jul 22 '05 #11
"Method Man" <a@b.c> wrote:
Q:
Write a C/C++ program that takes an unsigned integer and adds 1 to it
without using the plus or minus signs.


#include <functional>

unsigned addOne(unsigned x)
{
return std::plus<unsigned>()(x, 1);
}
Jul 22 '05 #12

"Method Man" <a@b.c> wrote in message news:Bt************@read1.cgocable.net...
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 another:

unsigned addOne(unsigned i)
{
switch(i) {
case 0: return 1;
case 1: return 2;
case 2: return 3;
case 3: return 4;
case 4: return 5;
case 5: return 6;
case 6: return 7;
case 7: return 8;
...
...

}
}

Jonathan
Jul 22 '05 #13

"Old Wolf" <ol*****@inspire.net.nz> skrev i en meddelelse
news:84**************************@posting.google.c om...
"Method Man" <a@b.c> wrote:
Q:
Write a C/C++ program that takes an unsigned integer and adds 1 to it
without using the plus or minus signs.


#include <functional>

unsigned addOne(unsigned x)
{
return std::plus<unsigned>()(x, 1);
}

This is by far the most elegant and efficient solution.

/Peter
Jul 22 '05 #14
Here's a fun recursive one:

unsigned int increment(unsigned int number) {
if (number & 1)
return inc1(number >> 1) << 1;

return number | 1;
}

And here's a truly evil one that only works if your chars are one-byte. :-)

unsigned int increment(unsigned int number) {
return (unsigned int)&((char*)number)[1];
}

Enjoy...

Justin Dubs
Jul 22 '05 #15

"Method Man" <a@b.c> wrote in message news:Bt************@read1.cgocable.net...
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.


Okay, just one more:

#include <iostream>

unsigned addOne(unsigned i)
{
std::cout << "Please enter the result of adding 1 to " << i << "\n";
unsigned result;
std::cin >> result;
return result;
}

Jonathan
Jul 22 '05 #16
Kid
da*********@aol.com (DaKoadMunky) wrote in message news:<20***************************@mb-m16.aol.com>...
I am curious to know if the gurus think that this kind of question has any use
beyond impressing girls at cocktail parties.

Would you actually deny somebody a C++ job if they couldn't answer this
question?

I ask because I consider myself to be an effective C++ developer but I
generally don't do well with this type of question or at the very least I feel
I have to put more thought into it than I think should be necessary.


Not modern C++ but definately C. Incrementing without a '+' token
isn't practical but is a decent test of one's bit twaddling skills.
Jul 22 '05 #17

"Peter Koch Larsen" <pk*****@mailme.dk> wrote in message

This is by far the most elegant and efficient solution.


But the least thought provoking too...
Jul 22 '05 #18

"Old Wolf" <ol*****@inspire.net.nz> schrieb im Newsbeitrag
news:84**************************@posting.google.c om...
"Method Man" <a@b.c> wrote:
Q:
Write a C/C++ program that takes an unsigned integer and adds 1 to
it
without using the plus or minus signs.


#include <functional>

unsigned addOne(unsigned x)
{
return std::plus<unsigned>()(x, 1);
}


Excellent! This one is the cleanest and best.
Jul 22 '05 #19

"Sharad Kala" <no******************@yahoo.com> skrev i en meddelelse
news:2r*************@uni-berlin.de...

"Peter Koch Larsen" <pk*****@mailme.dk> wrote in message

This is by far the most elegant and efficient solution.


But the least thought provoking too...

Not at all. It is the solution that understand how to take advantage of C++.
Most of the other solutions are simply C bit-fiddling, while some use C++
but in a most inefficient way (Jonathans std::vector).

/Peter
Jul 22 '05 #20
DaKoadMunky wrote:
I am curious to know if the gurus think that this kind of question has any use beyond impressing girls at cocktail parties.
I doubt that you can impress girls at cocktail parties with this kind
of
stuff. The use of this stuff is not really practical. It is more about
flexibility.
Would you actually deny somebody a C++ job if they couldn't answer this question?
I wouldn't ask for such a thing but if it became apparent that this
question could not be answered, I would probably indeed deny a C++
job. After all, the simple solution 'std::plus<int>()(n, 1)' should be
obvious to anybody knowing the standard C++ library... Funny that I saw
it mentioned only once before in this thread: this was first solution I
had in mind.
I ask because I consider myself to be an effective C++ developer but I generally don't do well with this type of question or at the very least I feel I have to put more thought into it than I think should be necessary.


Well, I could come up with a solution using bit logic but I would also
have to put more thought into it than I would like to spent. Thus, I
tend to come up with solutions which just take advantage of library
facilities.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting

Jul 22 '05 #21
* Dietmar Kuehl:
* DaKoadMunky:
Would you actually deny somebody a C++ job if they couldn't answer
this question?


I wouldn't ask for such a thing but if it became apparent that this
question could not be answered, I would probably indeed deny a C++
job. After all, the simple solution 'std::plus<int>()(n, 1)' should be
obvious to anybody knowing the standard C++ library... Funny that I saw
it mentioned only once before in this thread: this was first solution I
had in mind.


Probably because the question was C/C++ program, not C++ program (but I may be
wrong, just judging by my own response).

--
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?
Jul 22 '05 #22
#include <math.h>

void addOne(unsigned int &a) {
a = log(4 * exp(a));
}

Please, do remember to have sufficient exponent accuracy in
your floating point representation to cover the whole unsigned
int range.

Jul 22 '05 #23
Adding without loops:

void addOne(unsigned int &val) {
unsigned int x = ~val;
#define A(y) x &= (x & y) ? y : ~y;
A(0x0000ffff)
A(0x00ff00ff)
A(0x0f0f0f0f)
A(0x33333333)
A(0x55555555)
#undef A
val &= x * ~0;
val |= x;
}

Jul 22 '05 #24
"Gernot Frisch" <Me@Privacy.net> wrote in message news:<2r*************@uni-berlin.de>...
"Old Wolf" <ol*****@inspire.net.nz> schrieb im Newsbeitrag
news:84**************************@posting.google.c om...
"Method Man" <a@b.c> wrote:
Q:
Write a C/C++ program that takes an unsigned integer and adds 1 to
it
without using the plus or minus signs.


#include <functional>

unsigned addOne(unsigned x)
{
return std::plus<unsigned>()(x, 1);
}


Excellent! This one is the cleanest and best.


Given he didn't say which unsigned integer (overly pedantic hat) you
could go for some extra credit ;-)

#include <functional>

template< class T >
T add_one(T x)
{
return std::plus<T>()(x, 1);
}

matt.
www.hurd.com.au
Jul 22 '05 #25

"Jyrki Alakuijala" <Jy**************@find.me.via.google> schrieb im
Newsbeitrag news:ci**********@phys-news1.kolumbus.fi...
Adding without loops:

void addOne(unsigned int &val) {
unsigned int x = ~val;
#define A(y) x &= (x & y) ? y : ~y;
A(0x0000ffff)
A(0x00ff00ff)
A(0x0f0f0f0f)
A(0x33333333)
A(0x55555555)
#undef A
val &= x * ~0;
val |= x;
}

This one wins the obsfruscation contest...
Jul 22 '05 #26

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Anton Vredegoor | last post by:
While trying to solve Glen Wheelers problem I discovered an interesting puzzle. I'm going away for a day or so and it would be nice to have it solved when I'm back. It's about a different way to...
1
by: Developwebsites | last post by:
Hi all, I've made a sliding puzzle game in shockwave which works just fine, except I dont know how to have it solve itself. the URL is: http://members.aol.com/rglukov/games/selfsolve.htm ...
6
by: Laser Lu | last post by:
HI, all, I just want to invoke an internal method named 'ResolveClientUrl', which is defined in class System.Web.UI.Control, using an instance object of a type that derives from Control. Let's...
270
by: Jatinder | last post by:
I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles. Programming Puzzles Some companies certainly ask for these...
42
by: Frank Buss | last post by:
I've setup a challenge, mainly for C++, Java and Lisp, but every other language is welcome: http://www.frank-buss.de/challenge/index.html There is nothing to win, but I hope there will be some...
1
by: xavier vazquez | last post by:
I have a problem with a program that does not working properly...when the program run is suppose to generate a cross word puzzle , when the outcome show the letter of the words overlap one intop of...
0
by: xavier vazquez | last post by:
have a problem with a program that does not working properly...when the program run is suppose to generate a cross word puzzle , when the outcome show the letter of the words overlap one intop of the...
5
by: ashish0799 | last post by:
HI I M ASHISH I WANT ALGORYTHMUS OF THIS PROBLEM Jigsaw puzzles. You would have solved many in your childhood and many people still like it in their old ages also. Now what you have got to do...
4
by: honey777 | last post by:
Problem: 15 Puzzle This is a common puzzle with a 4x4 playing space with 15 tiles, numbered 1 through 15. One "spot" is always left blank. Here is an example of the puzzle: The goal is to...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.