本文共 1002 字,大约阅读时间需要 3 分钟。
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
public class Solution { public boolean isHappy(int n) { HashSetset = new HashSet<>(); set.add(n); int tmp = 0; while (n > 0) { tmp += (n % 10) * (n % 10); n = n / 10; } if (tmp == 1) return true; int new_n = tmp; while (!set.contains(new_n) && tmp != 1) { set.add(new_n); tmp=0; while (new_n > 0) { tmp += (new_n % 10) * (new_n % 10); new_n = new_n / 10; } new_n =tmp; } if(tmp ==1) return true; else return false; }}
转载地址:http://svuni.baihongyu.com/