-
Notifications
You must be signed in to change notification settings - Fork 1
/
palindrome-number.go
66 lines (51 loc) · 1.31 KB
/
palindrome-number.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
package algorithms
import "strconv"
func isPalindrome(x int) bool {
// When x < 0, x is not a palindrome
if x < 0 {
return false
}
// if the last digit of the number is 0 (x%10 == 0)
// the first digit of the number also needs to be 0
// Only 0 satisfy this property.
if x == 0 {
return true
}
if x%10 == 0 {
return false
}
// Convert the number to string
s := strconv.Itoa(x)
// Loop to check if we can read the same forward and backward.
// the middle digit doesn't matter in palindrome(it will always equal to itself)
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
if s[i] != s[j] {
return false
}
}
return true
}
// Solve without converting the integer to a string
func isPalindrome2(x int) bool {
// When x < 0, x is not a palindrome
if x < 0 {
return false
}
// if the last digit of the number is 0 (x%10 == 0)
// the first digit of the number also needs to be 0
// Only 0 satisfy this property.
if x == 0 {
return true
}
if x%10 == 0 {
return false
}
revertedNumber := 0
for x > revertedNumber {
revertedNumber = revertedNumber*10 + x%10
x /= 10
}
// When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
// Input is 12321 => we get x = 12, revertedNumber = 123/10 = 12
return x == revertedNumber || x == revertedNumber/10
}