-
Notifications
You must be signed in to change notification settings - Fork 375
/
Copy pathhappy_number_test.go
80 lines (64 loc) · 1.21 KB
/
happy_number_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
Problem:
- Write an algorithm to determine if a number is happy.
- Any number will be called a happy number if, after repeatedly replacing
it with a number equal to the sum of the square of all of its digits,
leads us to 1.
Example:
- Input: 19
Output: true
Explanation:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
Approach:
- Since the process always end in a cycle, we can use a similar approach to
finding a cycle in linked list problem.
- Once is cycle is found, check if it is stuck on 1.
Cost:
- O(n) time, O(1) space.
*/
package gtci
import (
"testing"
"github.com/hoanhan101/algo/common"
)
func TestIsHappy(t *testing.T) {
tests := []struct {
in int
expected bool
}{
{23, true},
{19, true},
{12, false},
}
for _, tt := range tests {
common.Equal(
t,
tt.expected,
isHappy(tt.in),
)
}
}
func isHappy(num int) bool {
slow, fast := num, num
for {
slow = squareSum(slow)
fast = squareSum(squareSum(fast))
if slow == fast {
break
}
}
return slow == 1
}
func squareSum(num int) int {
sum := 0
for num > 0 {
lastDigit := num % 10
sum += lastDigit * lastDigit
// get rid of last digit.
num /= 10
}
return sum
}