0
$\begingroup$

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

Function source.

asked Aug 17, 2022 at 19:45
$\endgroup$

1 Answer 1

0
$\begingroup$

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.

answered Aug 17, 2022 at 20:05
$\endgroup$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.