leetcode202: Happy Number

来源:互联网 发布:圣甲虫长板淘宝 编辑:程序博客网 时间:2024/05/21 11:31
要求:

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、计算一个int型变量的每一位的平方和

2、判断这个平方和是否为1


取出一个int的每一位的方法:n%10去除最低位的方法:n/10

在判断n是否大于零,控制整个while循环,这样就能完成第一个步骤


使用Set来存储使用过的n,如果发现执行几次循环后,出现了原来已经出现的值,而且这个值不等于1,那么说明n不是一个happy number。

为什么使用set? 因为set中含有contain方法,可以直接判断一个元素是否在set中,比较方便。(用ArrayList也是可以的)

    public boolean isHappy(int n) {       <span style="white-space:pre"></span>int sum = 0;HashSet<Integer> set = new HashSet<Integer>();while (true) {while (n > 0) {sum += Math.pow(n % 10, 2);n = n / 10;}if (set.contains(sum) && sum != 1)return false;else if (sum == 1)return true;set.add(sum);n = sum;sum = 0;    }


 


0 0
原创粉丝点击