一、题目
1、审题
2、分析
给出一个整数数字 n ,将其包含的每一位数字求平方最后求和,并赋值为 n,最终 n 为 1则称 n 为快乐数,若 n 不是快乐数,那他最终会陷入一个不会包含 1 的循环。判断 n 是不是一个快乐数。
二、解答
1、思路:
方法一、
通过设置两个指针,fast、slow。fast 每次运算两次,slow 每次运算一次,当 fast = slow 时跳出循环。
此时 fast == slow == 1 则 n 是快乐数;
若 fast == slow != 1,则 n 不是快乐数。
public boolean isHappy(int n) { int slow = n; int fast = n; do { slow = digitSquareSum(slow); fast = digitSquareSum(fast); fast = digitSquareSum(fast); } while(slow != fast); return slow == 1; } public int digitSquareSum(int n) { int sum = 0; while(n != 0) { sum += Math.pow(n % 10, 2); n /= 10; } return sum; }
方法二、
通过一个 Set 存储每次 n 运算后的数值,若运算时有 n = 1,则返回 true, 若未出现 n == 1 而出现添加失败即说明 n 运算出现了循环,应当返回 false;
public boolean isHappy2(int n) { Set<Integer> set = new HashSet<>(); int sum = 0; while(set.add(n)) { sum = 0; while(n > 0) { sum += Math.pow(n%10, 2); n /= 10; } if(sum == 1) return true; n = sum; } return false; }