首页 > 其他 > 详细

leetcode笔记:Power of Three

时间:2016-01-10 18:39:26      阅读:156      评论:0      收藏:0      [点我收藏+]

一. 题目描述

Given an integer, write a function to determine if it is a power of three.

Follow up: Could you do it without using any loop / recursion?

二. 题目分析

题目的大意很简单,给出一个整数,判断这个整数是不是3的整数次幂。下面提示尽量不适用循环和递归来实现,因此这里给出两种实现方法,其中第一种循环方式的耗时更少。

三. 示例代码

class Solution {
public:
    bool isPowerOfThree(int n) {
        while (n >= 1)
        {
            if (n == 1 || n == 3)
                return true;
            else
            {                
                if (n % 3) break;
                n /= 3;
            }
        }
        return false;
    }
};
class Solution {  
public:  
    bool isPowerOfThree(int n) {  
        if (n < 1) return 0;  

        int maxPow3 = log10(INT_MAX) / log10(3);
        int maxPow3Val = pow(3, maxPow3);  

        return maxPow3Val % n == 0;  
    }  
};

leetcode笔记:Power of Three

原文:http://blog.csdn.net/liyuefeilong/article/details/50492885

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!