zoukankan      html  css  js  c++  java
  • LeetCode 342. Power of Four

    https://leetcode.com/problems/power-of-four/

    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.

    Follow up: Could you solve it without loops/recursion?

    • 数学题+位运算。
    • 因为是signed 32 bits,所以先保证num > 0。
    • 然后2的幂的特征(num & (num - 1)) == 0,e.g. 0x1000 & 0x0111。
    • 再对2的幂中筛选不是4的幂的。4的幂的二进制中1总是出现在奇数位,e.g. 4^1(0x0100), 4^2(0x00010000), 4^3(0x01000000),其他则是在偶数位,e.g. 2^1(0x0010), 2^3(0x1000), 2^5(0x00100000)。所以(num & 0x55555555) != 0,这里0x55555555正是signed 32 bits integer。
    • 之前没注意位运算运算符&优先级低于==,需要加上括号。
    • C语言运算符_百度百科
      • http://baike.baidu.com/link?url=7D3QzeLlfI9pELy4OqJyyGE-WwRZhZ_mCI8ZSI6YdQHrldIIly3WnCTGnjzbypatAAodGjGFTUrTGJxkIbWFBq#2
    • 还有一种解法(4^n - 1)都可以被3整除,所以可以判断(num > 0) && ((num & (num - 1)) == 0) && ((num - 1) % 3 == 0)
     1 #include <iostream>
     2 using namespace std;
     3 
     4 class Solution {
     5 public:
     6     bool isPowerOfFour(int num) {
     7         return ((num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) != 0));
     8     }
     9 };
    10 
    11 int main ()
    12 {
    13     Solution testSolution;
    14     bool result;
    15     
    16     result = testSolution.isPowerOfFour(16);    
    17     cout << result << endl;
    18         
    19     char ch;
    20     cin >> ch;
    21     
    22     return 0;
    23 }
    View Code
  • 相关阅读:
    个人学期总结
    管理信息系统 第三部分 作业
    模型分离(选做)
    密码保护
    实现搜索功能
    完成个人中心—导航标签
    个人中心标签页导航
    评论列表显示及排序,个人中心显示
    完成评论功能
    ASP.NET Core开发者指南
  • 原文地址:https://www.cnblogs.com/pegasus923/p/5513242.html
Copyright © 2011-2022 走看看