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 = 1Credits: Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.
public class Solution { public boolean isHappy(int n) { List<Integer> list = new ArrayList<Integer>(); if (n == 0) return false; if (n == 1) return true; int temp = 0, sum = 0; while (true) { temp = n % 10; sum = sum + temp * temp; n = n / 10; if (n == 0) { if (sum == 1) return true; if (list.contains(sum)) return false; n = sum; list.add(sum); sum = 0; } } } }给两个别人的写法。
1.空间换时间
public boolean isHappy(int n) { if(n==0){ return false; } if(n==1){ return true; } int temp=0; boolean flag[]=new boolean[811]; int yushu=0; while(true){ while(n!=0){ yushu=n%10; n=n/10; temp+=yushu*yushu; } if(temp==1){ return true; } if(flag[temp]){ return false; }else{ flag[temp]=true; } n=temp; temp=0; } }2.大神之作。。。位运算,反正我是不会
public boolean isHappy(int n) { int[] mark = new int[8]; while (n > 1) { n = convert(n); if (n < 243) { int sec = n >> 5; int mask = 1 << (n & 0x1f); if ((mark[sec] & mask) > 0) { return false; } mark[sec] |= mask; } } return true; } private int convert(int n) { int sum = 0; while (n > 0) { int t = n % 10; sum += t * t; n /= 10; } return sum; }