友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
202. Happy Number
竟然可以使用"双指针",类似判断链表中是否有环的思路!妙!
Write an algorithm to determine if a number 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.
*Example: *
Input: 19
Output: true
Explanation:
1^2^ + 9^2^ = 82
8^2^ + 2^2^ = 68
6^2^ + 8^2^ = 100
1^2^ + 0^2^ + 0^2^ = 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Runtime: 1 ms, faster than 99.99% of Java online submissions for Happy Number.
*
* Memory Usage: 33.4 MB, less than 10.60% of Java online submissions for Happy Number.
*
* Copy from: https://leetcode.com/problems/happy-number/discuss/56917/My-solution-in-C(-O(1)-space-and-no-magic-math-property-involved-)[My solution in C( O(1) space and no magic math property involved ) - LeetCode Discuss]
*/
public boolean isHappy(int n) {
int slow = n;
int fast = n;
do {
slow = digitSquareSum(slow);
fast = digitSquareSum(fast);
fast = digitSquareSum(fast);
if (fast == 1) {
return true;
}
} while (slow != fast);
return false;
}
public int digitSquareSum(int n) {
int sum = 0;
while (n != 0) {
int temp = n % 10;
sum += temp * temp;
n /= 10;
}
return sum;
}