zoukankan      html  css  js  c++  java
  • LeetCode 326. Power of Three

    https://leetcode.com/problems/power-of-three/description/

    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。注意边界值。
    • 第二种解法,int最大值在C/C++语言中与机器位长相关,32位下是2^32-1,Java中int是固定的32位,即2^32-1。那么可以算出来int下最大的3的幂为3^19=1162261467。只要能被它整除的必然是3的幂。
      • https://leetcode.com/problems/power-of-three/solution/
     1 //
     2 //  main.cpp
     3 //  LeetCode
     4 //
     5 //  Created by Hao on 2017/3/16.
     6 //  Copyright © 2017年 Hao. All rights reserved.
     7 //
     8 
     9 #include <iostream>
    10 using namespace std;
    11 
    12 class Solution
    13 {
    14 public:
    15     bool isPowerOfThree(int n)
    16     {
    17         if (n < 1) {
    18             return false;
    19         }
    20         
    21         while (n % 3 == 0) {
    22             n /= 3;
    23         }
    24         
    25         return n == 1;
    26     }
    27 
    28     bool isPowerOfThree2(int n)
    29     {
    30         return n > 0 && 1162261467 % n == 0;
    31     }
    32 };
    33 
    34 int main(int argc, char* argv[])
    35 {
    36     Solution    testSolution;
    37     
    38     auto nums = {0, 1, 2, 3, 4, 6, 9, 27, 1162261467};
    39     
    40     for (auto num : nums)
    41     {
    42         cout << num << " isPowerOfThree ? " << testSolution.isPowerOfThree(num) << endl;
    43         cout << num << " isPowerOfThree2 ? " << testSolution.isPowerOfThree2(num) << endl;
    44     }
    45     
    46     return 0;
    47 }
    View Code
    0 isPowerOfThree ? 0
    0 isPowerOfThree2 ? 0
    1 isPowerOfThree ? 1
    1 isPowerOfThree2 ? 1
    2 isPowerOfThree ? 0
    2 isPowerOfThree2 ? 0
    3 isPowerOfThree ? 1
    3 isPowerOfThree2 ? 1
    4 isPowerOfThree ? 0
    4 isPowerOfThree2 ? 0
    6 isPowerOfThree ? 0
    6 isPowerOfThree2 ? 0
    9 isPowerOfThree ? 1
    9 isPowerOfThree2 ? 1
    27 isPowerOfThree ? 1
    27 isPowerOfThree2 ? 1
    1162261467 isPowerOfThree ? 1
    1162261467 isPowerOfThree2 ? 1
    Program ended with exit code: 0
    View Result
  • 相关阅读:
    用Intellij idea创建Maven项目JDK8源码阅读环境问题整理
    咱的Maven项目能用Junit5吗?
    43- 8 mvc知识点
    42-7 linq
    (Ant编程) Iqueryable 类型介绍
    Iqueryable 类型中 的 使用lambda 注意的坑。 (linq to sql)
    (Ant编程) Linq 的select 方法
    Scala模式匹配
    scala正则表达式
    P4336 [SHOI2016]黑暗前的幻想乡
  • 原文地址:https://www.cnblogs.com/pegasus923/p/8359630.html
Copyright © 2011-2022 走看看