快乐数
若将一个整数n的所有数字拆开分别平方後再相加,如此反覆进行至只剩个位数之後,其结果为1,则我们称n为快乐数
例如32→3^2+2^2=13
13→1^2+3^2=10
10→1^2+0^2=1
可以称32为快乐数
Input的第一个数字为测资个数
Output为Happy或Not Happy
例:
Input:
3
28
32
答案:
public class Solution { static List<String> result = new LinkedList<String>(); public static void main(String[] args) { Scanner scan = new Scanner(System.in); int num = scan.nextInt(); for(int i=0;i<num;i++){ if(isHappy(scan.nextInt())){ result.add("Happy"); }else{ result.add("Not Happy"); } } for(String i:result){ System.out.println(i); } } public static long sum_square(long n){ long sum = 0; while(n!=0){ sum += Math.pow(n%10,2); n = n/10; } return sum; } public static boolean isHappy(int n) { if(n<0) return false; long nn = n ; Set<Long> set = new HashSet<Long>(); while(true){ if(set.contains(nn)){ return false; } else{ set.add(nn); } nn = sum_square(nn); if(nn==1) return true; } } }