Puzzle: Add One Without Using + OR -

P

Peter Koch Larsen

Sharad Kala said:
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
 
A

Alf P. Steinbach

* Dietmar Kuehl:
* DaKoadMunky:


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).
 
J

Jyrki Alakuijala

#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.
 
J

Jyrki Alakuijala

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

Matt Hurd

Gernot Frisch said:
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
 
G

Gernot Frisch

Jyrki Alakuijala said:
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...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,176
Messages
2,570,947
Members
47,498
Latest member
log5Sshell/alfa5

Latest Threads

Top