-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,354
  • 2
  • 29
  • 51

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
  • 32,339
  • 4
  • 44
  • 73
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
  • 740,318
  • 145
  • 1,296
  • 1,325