码迷,mamicode.com
首页 > 其他好文 > 详细

Power of Four(Difficulty: Easy)

时间:2016-05-06 19:13:56      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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.

实现:

1 class Solution {
2 public:
3     bool isPowerOfFour(int num) {
4         return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) == num);
5     }
6 };

分析:

(num & (num - 1)) == 0 判断这个数是不是2的倍数,(num & 0x55555555) == num 判断是不是4的倍数。0x55555555就是二进制数上奇数位上为1.

Power of Four(Difficulty: Easy)

标签:

原文地址:http://www.cnblogs.com/lrh-xl/p/5462456.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!