-3

What is the fastest (in asymptotic worst-case time complexity) algorithm for determining if a sum of arbitrary positive integers is a power of two?

Elliot Gorokhovsky
  • 3,610
  • 2
  • 31
  • 56

2 Answers2

2

One cute bit twiddling trick is to test if x&(x-1) is equal to 0.

Note that you need to decide what to do if x is equal to 0, this test will mark 0 as a power of 2 so you may want an exception for this case.

Peter de Rivaz
  • 33,126
  • 4
  • 46
  • 75
1

Subtract 1 from the sum and perform a bitwise AND with the original number. Powers of 2 will have a result of 0.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358