全球彩票平台_全球彩票注册平台|官网下载地址

热门关键词: 全球彩票平台,全球彩票注册平台,全球彩官网下载地址

【全球彩票注册平台】Power of Four,poweroffour

Power of Four,poweroffour

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.

【全球彩票注册平台】Power of Four,poweroffour。Follow up: Could you solve it without loops/recursion?

4的幂次方 二进制里唯有1个1

认清二进制里有未有1个1 用n & (n-1)== 0    

 

1 bool isPowerOfFour(int num) {
2     if(num <= 0) return false;
3     if(num & (num - 1)) return false; 
4     if(num & 0x55555555) return true; // 再将不是 4 的 N 次方的数字去掉
5     return false;
6 }

 

of Four,poweroffour 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 fal...

leetcode342——Power of Four(C ),leetcode342four

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个1的时候,即必为2的幂时,怎么样越发判别它是还是不是4的幂。

  1.  8ms

    class Solution { public:

     bool isPowerOfFour(int num) {
         if(num<=0)
             return false;
         if((num&(num-1))!=0)          //判断是不是2的幂,或者说二进制是否只有1个1
             return false;
         if((num-1)%3==0)        //判断这个1的位置,来判断是不是4的幂
             return true;
         return false;
     }
    

    };

为何要使用num-1后能或不能够整除3论断,很四个人各类数学注脚,其实从二进制角度很好通晓声明。num减1后获取的数字末尾全为1,3的二进制是……11,那么从压低位算起有偶数个1的数字都能整除3,奇数个不可能整除。自然4的幂减1后为偶数个1。

  1.  8ms

    class Solution { public:

     bool isPowerOfFour(int num) {
         if(num<=0)
             return false;
         if((num&(num-1))!=0)
             return false;
         int con=0x55555555;
         if((num&con)!=0)
             return true;
         return false;
     }
    

    };

此处运用了多个数字0x55555555,它是01010101……01010101。4的幂二进制中的1的岗位一定出现在0x55555555二进制1的职分,那么按位与操作后等于0表明地点不对,那就不是4的幂。

of Four(C ),leetcode342four Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example: Given num = 16, return t...

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

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

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.

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

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

本文由全球彩票平台发布于全球彩票注册平台编程,转载请注明出处:【全球彩票注册平台】Power of Four,poweroffour

TAG标签: 全球彩票平台
Ctrl+D 将本页面保存为书签,全面了解最新资讯,方便快捷。