Power of Four

By | April 19, 2016
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example:
Given num = 16, return true. Given num = 5, return false.

Solution. This is another good one for bit manipulation.

First of all, any negative number should return false.

2nd, we can use num & (-num) to test if binary form only has one 1. In another word, to see if num is power of 2.

In the end, because power of four only has 1 in odd position:
1
100
10000
1000000
To test if 1 exists at odd position, we need to use num & 0x55555555

The final answer is return (num & (num 1)) == 0 && (num & 0x55555555) != 0;

Check my code on github: link

  • junmin liu

    hmm…. what you said in the blog is different from what you coded in the github. ….

    • http://www.allenlipeng47.com peng li

      Right. There is no necessary to do num & (-num). I just did update.