zoukankan      html  css  js  c++  java
  • Leetcode题目:Power of Three

    题目: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的幂。可以从以下的数列中观察出规律:

    (1)3^0 = 1

    (2)3^1 = 3

    (3)3^2 = 9

    (4)3^3 = 27

    (5)3^4 = 81

    ……

    可以发现所有3的幂指数,互相之间都是可以整除的关系。即3^n 一定可以被 3^m 整除,若有m <= n。

    那么,我们可以找到int范围内可以存储的最大的3的幂1162261467 = 3^19。如果num可以整除它,那么num就是3^x。

    代码如下:

    class Solution {
    public:
        bool isPowerOfThree(int n) {
            return ((n > 0) && (1162261467 % n == 0)) ? true : false;
        }
    };

  • 相关阅读:
    codesmith
    moment.js
    select2
    Lodash js数据操作库
    angular.js
    vue.js
    axios.js
    RoutePrefix和Route 路由前缀
    Tuple元组 C#
    ningx访问日志切割
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5417593.html
Copyright © 2011-2022 走看看