202.Happy Number
Write an algorithm to determine if a number n is “happy”.
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Return True if n is a happy number, and False if not.
Example:
分析
构造一个求一个正整数的各位平方和的函数,已知是一个循环过程,所以可以运用快慢标识来计算,当快慢标识的数相等时,判断值是否为1,是的话输出true,否则输出false。
代码
#include<iostream>
using namespace std;
class Solution {
public:
int getNum(int n) {
int sum = 0;
while(n) {
sum += (n % 10)*(n % 10);
n = n / 10;
}
return sum;
}
bool isHappy(int n) {
int slow = n;
int fast = n;
do {
slow = getNum(slow);
fast = getNum(fast);
fast = getNum(fast);
} while (slow != fast);
return slow == 1 ? true : false;
}
};
int main() {
int i;
Solution s;
for (i = 1; i < 100; i++) {
if (s.isHappy(i))
printf("%d ", i);
}
return 0;
}
时间复杂度与空间复杂度分析
时间复杂度 | 空间复杂度 |
---|---|
O(n) | O(1) |