题目:

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.

相关文章:

  • 2022-01-24
  • 2022-12-23
  • 2021-04-10
  • 2022-12-23
  • 2021-11-29
  • 2021-06-02
  • 2022-02-17
  • 2022-01-04
猜你喜欢
  • 2022-12-23
  • 2021-04-15
  • 2021-04-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-10
相关资源
相似解决方案