202. Happy Number

来源:互联网 发布:网络舞曲dj串烧视频 编辑:程序博客网 时间:2024/06/14 05:40

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

public class Solution {public boolean isHappy(int n) {Set<Integer> set = new HashSet<Integer>();int quadraticSum = 0;// set集合有个特性,在向set集合中添加元素时,如果存在,返回false,如果不存在,返回true// 所以以set再能否添加数据为循环条件while (set.add(n)) {quadraticSum = getQuadraticSum(n);if ( quadraticSum == 1 ) {return true;}n = quadraticSum;}return false;}// 用来计算一个数按位被拆开后的平方和public int getQuadraticSum(int n) {int sum = 0;while ( n != 0) {int temp = n % 10;sum += Math.pow(temp, 2);n = n / 10;}return sum;}}

原创粉丝点击