目錄
- LeetCode 507:完美數
- 分析
- 代碼
- 偷雞法
- LeetCode 263:丑數|
- 分析
- 代碼
LeetCode 507:完美數
原題鏈接: LeetCode 507:完美數

分析
怎么求出一個數的因子,從1 到 sqrt(n)開始列舉,因為如果 因子大于sqrt(n)的話另一個因子就會小于sqrt(n),避免重復計算
每次遍歷時將兩個因子累加起來,
代碼
bool checkPerfectNumber(int num)
{
if (num == 1)
return false;
int sum = 0;
for (int i = 1; i * i <= num; ++i)
{
if (num % i == 0)
{
sum += i;
if (i * i != num)
sum += num / i;
}
}
sum -= num;
return sum == num;
}
偷雞法
看到評論區有的哥們欺負完美數少,直接用的打表計算
bool checkPerfectNumber(int num)
{
switch(num)
{
case 6:
case 28:
case 496:
case 8128:
case 33550336:
return true;
}
return false;
}
其實結果都差不多的

LeetCode 263:丑數|
鏈接: 263.丑數1

分析
用比較老實的方法,因為丑數因子都是2,3,5;
那我只要拿給出的數一直除以2,3,5,到最后如果結果為1,就說明是丑數,
代碼
bool isUgly(int n)
{
if (n < 1)
return false;
while (n % 2 == 0)
{
n /= 2;
}
while (n % 3 == 0)
{
n /= 3;
}
while (n % 5 == 0)
{
n /= 5;
}
return n == 1;
}
運行結果:

感謝大家觀看
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/342038.html
標籤:其他
