未分類

Palindrome Number

Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

提示 解題應用 額外的Package
Math 字串、型別 strconv

Default:

1
2
func isPalindrome(x int) bool {
}

解答思路:

回文,從文本前面讀起或從後面往回看兩者的結果都會一樣,例如:abcba,此題是以數字來做回文,所以我們馬上就可以知道如果收到的值為負數,則必不可能回文,總不可能丟進來的值是-12321-這種搞笑值吧!而檢查方式我想很容易就可以想到,只要以對稱的方式來做檢查,即頭對尾以此類推便可以很容易搞定。

程式碼解說:

將數字轉換成字串之後,從頭一一取值去與尾數(index: 長度-(index+1)) )做比較,若發現不一樣就直接回傳false直到整個流程沒有問題才回傳true。

1
2
3
4
5
6
7
8
str := strconv.Itoa(x)
slen := len(str)
for key, value := range str {
if value != rune(str[slen-(key+1)]) {
return false
}
}
return true

完整程式碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func isPalindrome(x int) bool {
if x < 0 {
return false
} else {
str := strconv.Itoa(x)
slen := len(str)
for key, value := range str {
if value != rune(str[slen-(key+1)]) {
return false
}
}
return true
}
}

總結:

回文,以前、後對稱的方式做檢查即可。

分享到