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
  • 相关阅读:
    PHP数据库备份文件分卷导入的实现思路
    用delphi如何实现启动停止windows服务
    【创意logo】第23个世界无烟日 让烟草远离女性
    修改“windows xp资源管理器”的默认打开路径
    PHP百行代码快速构建简易聊天室
    简单的方法实现判断Mysql内某个字段Fields是否存在
    Blackhand的插件管理部分
    PHP 与 ASP.NET 正面交锋
    C语言运算符
    功能齐全的发送邮件类
  • 原文地址:https://www.cnblogs.com/pegasus923/p/8359630.html
Copyright © 2011-2022 走看看