15算法课程 342. 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?


solution:

循环。任一个数如果是4的幂,则重复除以4的话最后会得到一个1。例:64/4=16,16/4=4,4/4=1。且除的过程中全部都是整除,没有余数。可以用这个思路判断num是不是4的幂。


code:

class Solution {
public:
    bool isPowerOfFour(int num) {
        if(num==0)
          return false;
        while(num!=1&&num%4==0){
               num=num/4;
        }
        if(num==1)
           return true;
        else
           return false;
    }
};


猜你喜欢

转载自blog.csdn.net/QingJiuYou/article/details/78877570
今日推荐