[LeetCode]326. Power of Three ★

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/xingyu97/article/details/100180730

题目描述

Given an integer, write a function to determine if it is a power of three.
题目大意:给定一个整数,判断这个整数是否是3
的n次幂

样例

Example 1:

Input: 27
Output: true

Example 2:

Input: 0
Output: false

Example 3:

Input: 9
Output: true

Example 4:

Input: 45
Output: false

python解法

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        return n>0 and 1162261467 % n == 0

Runtime: 96 ms
Memory Usage: 13.9 MB
题后反思:

  1. 这应该是最简单的一种写法了,但却不是最快的写法。
  2. 1162261467是32位有符号整数里面可接受的3的次幂最大的整数。

C语言解法

bool isPowerOfThree(int n){
    return n>0?1162261467 % n == 0:false;
}

Runtime: 12 ms, faster than 82.84% of C online submissions for Power of Three.
Memory Usage: 7.5 MB, less than 50.00% of C online submissions for Power of Three.
题后反思:无

bool isPowerOfThree(int n){
    while(n>2)
    {
        if (n%3)
            return false;
        n /= 3;
    }
    return n == 1;
}

Runtime: 24 ms
Memory Usage: 7.5 MB

文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步

猜你喜欢

转载自blog.csdn.net/xingyu97/article/details/100180730