|
| 1 | +package by.andd3dfx.numeric; |
| 2 | + |
| 3 | +import java.util.HashSet; |
| 4 | +import java.util.Set; |
| 5 | + |
| 6 | +/** |
| 7 | + * <pre> |
| 8 | + * <a href="https://leetcode.com/problems/happy-number/description/">Task description</a> |
| 9 | + * |
| 10 | + * Write an algorithm to determine if a number n is happy. |
| 11 | + * A happy number is a number defined by the following process: |
| 12 | + * Starting with any positive integer, replace the number by the sum of the squares of its digits. |
| 13 | + * Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. |
| 14 | + * Those numbers for which this process ends in 1 are happy. |
| 15 | + * Return true if n is a happy number, and false if not. |
| 16 | + * |
| 17 | + * Example 1: |
| 18 | + * Input: n = 19 |
| 19 | + * Output: true |
| 20 | + * Explanation: |
| 21 | + * 12 + 92 = 82 |
| 22 | + * 82 + 22 = 68 |
| 23 | + * 62 + 82 = 100 |
| 24 | + * 12 + 02 + 02 = 1 |
| 25 | + * |
| 26 | + * Example 2: |
| 27 | + * Input: n = 2 |
| 28 | + * Output: false |
| 29 | + * </pre> |
| 30 | + */ |
| 31 | +public class HappyNumber { |
| 32 | + |
| 33 | + public static boolean isHappyUsingMemory(int n) { |
| 34 | + Set<Integer> set = new HashSet<>(); |
| 35 | + |
| 36 | + var tmp = getSumOfSquares(n); |
| 37 | + while (tmp != 1 && set.add(tmp)) { |
| 38 | + tmp = getSumOfSquares(tmp); |
| 39 | + } |
| 40 | + return tmp == 1; |
| 41 | + } |
| 42 | + |
| 43 | + public static boolean isHappyUsing2Pointers(int n) { |
| 44 | + var p1 = getSumOfSquares(n); |
| 45 | + var p2 = getSumOfSquares(p1); |
| 46 | + |
| 47 | + do { |
| 48 | + // p1: 1 step |
| 49 | + p1 = getSumOfSquares(p1); |
| 50 | + |
| 51 | + // p2: 2 steps |
| 52 | + p2 = getSumOfSquares(p2); |
| 53 | + if (p1 == p2) { |
| 54 | + return p1 == 1; |
| 55 | + } |
| 56 | + p2 = getSumOfSquares(p2); |
| 57 | + if (p1 == p2) { |
| 58 | + return p1 == 1; |
| 59 | + } |
| 60 | + } while (true); |
| 61 | + } |
| 62 | + |
| 63 | + private static int getSumOfSquares(int n) { |
| 64 | + var result = 0; |
| 65 | + while (n > 0) { |
| 66 | + var remainder = n % 10; |
| 67 | + result += remainder * remainder; |
| 68 | + n /= 10; |
| 69 | + } |
| 70 | + return result; |
| 71 | + } |
| 72 | +} |
0 commit comments