File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * @lc app=leetcode id=202 lang=java
3+ *
4+ * [202] Happy Number
5+ *
6+ * https://leetcode.com/problems/happy-number/description/
7+ *
8+ * algorithms
9+ * Easy (46.28%)
10+ * Likes: 998
11+ * Dislikes: 264
12+ * Total Accepted: 260.4K
13+ * Total Submissions: 561.6K
14+ * Testcase Example: '19'
15+ *
16+ * Write an algorithm to determine if a number is "happy".
17+ *
18+ * A happy number is a number defined by the following process: Starting with
19+ * any positive integer, replace the number by the sum of the squares of its
20+ * digits, and repeat the process until the number equals 1 (where it will
21+ * stay), or it loops endlessly in a cycle which does not include 1. Those
22+ * numbers for which this process ends in 1 are happy numbers.
23+ *
24+ * Example:
25+ *
26+ *
27+ * Input: 19
28+ * Output: true
29+ * Explanation:
30+ * 1^2 + 9^2 = 82
31+ * 8^2 + 2^2 = 68
32+ * 6^2 + 8^2 = 100
33+ * 1^2 + 0^2 + 0^2 = 1
34+ *
35+ */
36+ class Solution {
37+ public boolean isHappy (int n ) {
38+ Set <Integer > set = new HashSet <>();
39+ while (n != 1 && !set .contains (n )) {
40+ set .add (n );
41+ n = sumOfDigits (n );
42+ }
43+ return (n == 1 ) ? true : false ;
44+ }
45+
46+ public int sumOfDigits (int n ) {
47+ int sum = 0 ;
48+ while (n != 0 ) {
49+ sum += (n %10 ) * (n %10 );
50+ n /= 10 ;
51+ }
52+ return sum ;
53+ }
54+ }
55+
You can’t perform that action at this time.
0 commit comments