Just a fun puzzle that occurred to me. Given the function below which converts decimal integers to binary strings, is it possible to predict which decimal numbers will lead to binary strings with no zeros?
I.e. is there a way to ensure this function only returns strings of 1s without building the string and checking?
std::string toBinary(int n){
std::string r;
while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
return r;
}
1 Answer 1
A binary string with only 1's represents a number that is a power of 2 minus one.
So if the rules allow to test whether a decimal number is a power of two then the solution is to add one to the number and keep deviding it by two and checking whether the remainder is zero in each step.