1. 程式人生 > 其它 >LeetCode - Easy - 202. Happy Number

LeetCode - Easy - 202. Happy Number

技術標籤:LeetCode演算法與資料結構mathhash table

Topic

  • Math
  • Hash Table

Description

https://leetcode.com/problems/happy-number/

Write an algorithm to determine if a number n 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.
  • 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.

Return true if n is a happy number, and false if not.

Example 1:

Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Example 2:

Input: n = 2
Output: false

Constraints:

  • 1 <= n <= 2³¹ - 1

Analysis

方法一:關鍵用雜湊表快取中間計算結果。

方法二:快慢指標查環思路。

Submission

import java.util.HashSet;
import java.util.Set;

public class HappyNumber {

	// 方法一:
	public boolean isHappy1(int n) {
		if (n < 1) return false;
		Set<Integer>
cache = new HashSet<>(); while (!cache.contains(n)) { cache.add(n); int sum = 0; while (n > 0) { int temp = n % 10; sum += temp * temp; n /= 10; } if ((n = sum) == 1) return true; } return false; } // 方法二: public boolean isHappy2(int n) { int slow, fast; slow = fast = n; do { slow = digitSquareSum(slow); fast = digitSquareSum(fast); if (fast == 1) return true; fast = digitSquareSum(fast); if (fast == 1) return true; } while (slow != fast); return false; } private int digitSquareSum(int n) { int sum = 0, tmp; while (n > 0) { tmp = n % 10; sum += tmp * tmp; n /= 10; } return sum; } }

Test

import static org.junit.Assert.*;
import org.junit.Test;

public class HappyNumberTest {

	@Test
	public void test() {
		HappyNumber obj = new HappyNumber();
		
		assertTrue(obj.isHappy1(19));
		assertFalse(obj.isHappy1(2));
		
		assertTrue(obj.isHappy2(19));
		assertFalse(obj.isHappy2(2));
	}
}