Answers

Question and Answer:

  Home  Analyst Integration

⟩ How do you find if a number is power of two, without using arithmetic operator?

Assume its a question about using bitwise operator as soon as you hear restriction about not allowed to use arithmetic operator. If that restriction is not in place then you can easily check if a number is power of two by using modulus and division operator. By the using bitwise operator, there is a nice trick to do this. You can use following code to check if a number if power of two or not

public static boolean powerOfTwo(int x) {

return (x & (x - 1)) == 0;

}

x & (x-1) is a nice trick to convert right most bit to zero if it's on, I learned from hackers delight book.

 155 views

More Questions for you: