package com.bupt; import java.util.HashSet; //最重要的理解的内容就是对一个数要吗成为快乐数,要吗进入死循环(试几个数就会发现。),不会出现越来越大的情况 //通过举例9,99,999可以发现 public class T202 { int f(int mul,int n){ int s = 0; while (true){ s = n%10; mul+=s*s; n = n/10; if(n<1) break;; } return mul; } //第一种,暴力 public boolean isHappy(int n) { int mul =0; for (int i = 0; i < 100; i++) { n = f(mul,n); if(n==1) break; } if(n==1) return true; else return false; } //第二种快慢指针 ,如果是循环的话,快指针会追到满指针 public boolean isHappy1(int n) { int slow = n; int fast = f(0,n); while (fast!=1 && fast!=slow){ slow = f(0,slow); fast = f(0,f(0,fast)); } if(fast==1) return true; else return false; } //第三种hash表记录 public boolean isHappy2(int n) { HashSet<Integer> ints = new HashSet<>(); boolean flag = false; while (true){ n = f(0,n); if(ints.contains(n)==true){ flag = false; break; }else{ ints.add(n); } if(n==1) { flag = true; break; } } return flag; } public static void main(String[] args) { System.out.println(new T202().isHappy2(20)); } }