This solution was originally binary and converted to ordinary math as the specified requester.
It will make more sense as binary, at least multiply by 2 and divide by 2, should be <<1 and β 1 for speed, addition and subtraction probably do not matter in one form or another.
If you pass the mask instead of nBits and use bitrate instead of multiplication or division and change the tail recursion to a loop, this will probably be the most efficient solution you will find, since every other call will be nothing but one addition, it will only be so slow. as Alnitakβs solution, every 4, maybe even 8 calls.
int incrementBizarre(int initial, int nBits) // in the 3 bit example, this should create 100 mask=2^(nBits-1) // This should only return true if the first (least significant) bit is not set // if initial is 011 and mask is 100 // 3 4, bit is not set if(initial < mask) // If it was not, just set it and bail. return initial+ mask // 011 (3) + 100 (4) = 111 (7) else // it was set, are we at the most significant bit yet? // mask 100 (4) / 2 = 010 (2), 001/2 = 0 indicating overflow if(mask / 2) > 0 // No, we were't, so unset it (initial-mask) and increment the next bit return incrementBizarre(initial - mask, mask/2) else // Whoops we were at the most significant bit. Error condition throw new OverflowedMyBitsException()
Wow, it turned out pretty cool. I did not figure in recursion until the last second.
It doesnβt feel right - for example, there are some operations that should not work, but they do because of the nature of what you are doing (for example, it seems like you have to worry when you work a little and some bits to the left are different from zero, but it turns out that you can never work on a bit if all the bits to the left are equal to zero - this is a very strange condition, but true.
An example of a flow to obtain from 110 to 001 (3 back to 4):
mask 100 (4), initial 110 (6); initial < mask=false; initial-mask = 010 (2), now try on the next bit mask 010 (2), initial 010 (2); initial < mask=false; initial-mask = 000 (0), now inc the next bit mask 001 (1), initial 000 (0); initial < mask=true; initial + mask = 001--correct answer