TypechoJoeTheme

# 顿搜  # [LeetCode 202] Happy Number [Java] [Runtime : 5MS] 2017-09-02
/
0 评论
/
494 阅读
/

09/02

## 1. Description

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.

## 2. Runtime Distribution ## 3. Submission Details ## 4. Example

19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

## 5. Code

private HashSet<String> set = new HashSet<String>();

public boolean isHappy(int n) {
if (n <= 0) {
return false;
}

if (n == 1) {
return true;
}

String num = String.valueOf(n);

if (set.contains(num)) {
return false;
}

int sum = 0;
for (int i = 0; i < num.length(); i++) {
int tmp = num.charAt(i) - '0';
sum += tmp * tmp;
}
return isHappy(sum);
}

## 6.Test

import java.util.HashSet;

public class LeetCode0202 {

private HashSet<String> set = new HashSet<String>();

public boolean isHappy(int n) {
if (n <= 0) {
return false;
}

if (n == 1) {
return true;
}

String num = String.valueOf(n);

if (set.contains(num)) {
return false;
}

int sum = 0;
for (int i = 0; i < num.length(); i++) {
int tmp = num.charAt(i) - '0';
sum += tmp * tmp;
}
return isHappy(sum);
}

public static void main(String[] args) {
LeetCode0202 leetcode = new LeetCode0202();
System.out.println(leetcode.isHappy(19));
}
}
Math

https://dun.so/archives/799/（转载时请注明本文出处及文章链接） 顿搜

392 文章数
45 评论量

• 获取失败！

### 最新回复

1. Volusus
2022-03-21
2. ljpww72729
2016-08-31
3. zhu
2016-04-26
4. X·舞~V~
2016-01-26
5. X·舞~V~
2016-01-26