-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpalindrome-number.go
More file actions
39 lines (33 loc) · 826 Bytes
/
palindrome-number.go
File metadata and controls
39 lines (33 loc) · 826 Bytes
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
package main
import "fmt"
/*
source: https://leetcode.com/problems/palindrome-number/
problem: Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
For example, 121 is a palindrome while 123 is not.
-231 <= x <= 231 - 1
*/
// go digit by digit from the both sides of the number and compare them
func isPalindrome1(x int) bool {
if x < 0 {
return false
}
strX := fmt.Sprint(x)
for i, _ := range strX[:len(strX)/2] {
if strX[i] != strX[len(strX)-1-i] {
return false
}
}
return true
}
// flip the number and check if flipped one is equal to the source one
func isPalindrome(x int) bool {
if x < 0 {
return false
}
flippedX := 0
for dx := x; dx > 0; dx /= 10 {
flippedX = flippedX*10 + dx%10
}
return flippedX == x
}