[LeetCode][数论]Happy Number

来源:互联网 发布:数据质量考核办法 编辑:程序博客网 时间:2024/04/28 04:12

题目描述:

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
思路:
前提:幸福数的每个位上数字的平方和最终一定为1,如果不为1继续拆分当前数,求其各个数位的平方和
过程:各个位的平方和必然需要拆分数字,然后求平方和,借助java字符串进行位的分离是最常用的方法,难点在于无限循环下去如何控制,这个时候可以基于一些现成的数据结构,例如HashSet,每创建一个数就加入HashSet,如果HashSet数据量大到无法插入,则返回false,借助数据结构来帮我们判断是否有足够的内存空间来存放数据

代码实现:
public class Solution {    public boolean isHappy(int n) {       Set<Integer> numberSet = new HashSet<Integer>();              while(n!=1){           if(numberSet.add(n)==false){               return false;           }           char[] chars = String.valueOf(n).toCharArray();           int total = 0;           for(Character ch:chars){               total += Math.pow(Integer.parseInt(ch+""),2);           }           n = total;       }       return true;    }}



0 0
原创粉丝点击