Happy Number
https://leetcode.com/problems/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
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
Credits:
Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.
1 import java.util.HashSet; 2 import java.util.Set; 3 4 public class Solution { 5 public static boolean isHappy(int n) { 6 if(n==1){return true;} 7 Set<Integer>set=new HashSet(); 8 int result=0; 9 while(result!=1){ 10 result=0; 11 String x=n+""; 12 int len=x.length(); 13 for(int i=0;i<len;i++){ 14 char c=x.charAt(i); 15 result+=(c-'0')*(c-'0'); 16 } 17 if(set.contains(result)){return false;} 18 set.add(result); 19 n=result; 20 } 21 return true; 22 } 23 public static void main(String[]args){ 24 System.out.println(isHappy(19)); 25 } 26 }