3

What is the most efficient (in terms of speed and space) way to check if a decimal number only has a single '1' in its binary representation without using special functions (math, numpy, etc.)?

e.g. 1 is '001' and 4 is '100'.

I've tried this

binary  =  "{0:b}".format(value)
if binary.count('1') != 1:
    return 1
else:
    return 0

I believe this is O(log n) in terms of space and O(n) in terms of speed? Is there a way to do this more efficiently?

mayankmehtani
  • 435
  • 4
  • 14

1 Answers1

1

One of the method to do it could be-

binary_num = '00101010'
result = [1 for x in binary_num if x == '1']
if len(result) == 1:
    print('Success')
else:
    print('Failed')
Chetan Goyal
  • 435
  • 5
  • 14