[LeetCode]202. Happy Number

知是行的主意,行是知的功夫。这篇文章主要讲述[LeetCode]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: 19 is a happy number

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
【[LeetCode]202. Happy Number】思路:
思路:一个快乐数指的是各位数字的平方的和加起来,不断计算,最终收敛为1。对于某一个正整数,如果对其各个位上的数字分别平方,
然后再加起来得到一个新的数字,再进行同样的操作,如果最终结果变成了1,则说明是快乐数,如果一直循环但不是1的话,就不是快乐数,否则会陷入死循环。
给出一个整数,判断是否为快乐数。
如果不是快乐数。如11,计算过程如下:
1^2 + 1^2 = 2
2^2 = 4
4^2 = 16
1^2 + 6^2 = 37
3^2 + 7^2 = 58
5^2 + 8^2 = 89
8^2 + 9^2 = 145
1^2 + 4^2 + 5^2 = 42
4^2 + 2^2 = 20
2^2 + 0^2 = 4
会陷入4的死循环
可以用set来记录所有出现过的数字,然后每出现一个新数字,在set中查找看是否存在,若不存在则加入表中,
若存在则跳出循环,并且判断此数是否为1,若为1返回true,不为1返回false
set中不存在重复的对象
首先判断是否小于0.小于0则返回false
当n不等于1时,将n存储到set内,对n计算各位数字的平方和,记为新的n。判断n是否在set中出现过,如果出现过则表示陷入循环了。返回false
否则将n存入set中去,继续判断新的n

第二种方法是:
非快乐数必然在循环中出现4,只需判断是否在循环中n出现过4,出现则false

1 public class Solution202 { 2public boolean isHappy(int n) { 3HashSet< Integer> set= new HashSet< > (32); 4if(n < = 0) return false; 5while(n!=1){ 6int tmp = 0; 7set.add(n); 8while(n> 0){ 9tmp+=(n%10)*(n%10); 10n/=10; 11} 12n = tmp; 13if(set.contains(n)) break; 14else { 15set.add(n); 16} 17} 18return n == 1; 19/*第二种方法:判断循环中是否出现4即可 20while (n != 1 & & n != 4) { 21int t = 0; 22while (n> 0) { 23t += (n % 10) * (n % 10); 24n /= 10; 25} 26n = t; 27} 28return n == 1; 29*/ 30} 31public static void main(String[] args) { 32// TODO Auto-generated method stub 33Solution202 solution202 = new Solution202(); 34int n = 19; 35System.out.println(solution202.isHappy(n)); 36} 37 38 }

 

































    推荐阅读