[Leetcode] Power of Three

本文介绍两种方法来判断一个整数是否为3的幂。第一种方法使用除数法,通过不断除以3直到无法整除,检查最终结果是否为1。第二种方法利用整型数特点,通过计算最大可能的3的幂值(1162261467),检查该值是否能被待判断的数整除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

判断一个数是否为3的幂:

一,除数法,最容易想到的方法:

1. 首先是能够整除

2. 整除到最后的数一定为1则说明TRUE否则FALSE

bool isPowerOfThree(int n) {
    if (n <= 0)
        return false;
    
    while(0 == (n % 3)){
        n/=3;
    }    
    
    return (n == 1);
}
二,根据整型数的特点,总结规律

boolean isPowerOfThree(int n) {
        return (n > 0) && (1162261467 % n == 0);
}

引用从解答中的分析:

  • MaxInt = \frac{ 2^{32} }{2} - 122321 since we use 32 bits to represent the number, half of the range is used for negative numbers and 0 is part of the positive numbers

Knowing the limitation of n, we can now deduce that the maximum value of n that is also a power of three is 1162261467. We calculate this as:

3^{\lfloor{}log_3{MaxInt}\rfloor{}} = 3^{\lfloor{}19.56\rfloor{}} = 3^{19} = 11622614673log3MaxInt=319.56=319=1162261467

Therefore, the possible values of n where we should return true are 3^0303^131 ... 3^{19}319. Since 3 is a prime number, the only divisors of 3^{19}319 are 3^0303^131 ... 3^{19}319, therefore all we need to do is divide 3^{19}319 by n. A remainder of 0 means n is a divisor of 3^{19}319 and therefore a power of three.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值