Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode-9. Palindrome Number #16

Closed
ninehills opened this issue Jul 20, 2017 · 0 comments
Closed

LeetCode-9. Palindrome Number #16

ninehills opened this issue Jul 20, 2017 · 0 comments
Labels

Comments

@ninehills
Copy link
Owner

ninehills commented Jul 20, 2017

20170720

问题

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

click to show spoilers.

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.

思路

回文数类似于 12321,或者 123321。两种思路:

  • 转换数字到字符串后,进行判断
  • 把数字逆序后,看看是否相等,相等就为回文数

解答

package main

import "fmt"

// ----------------------

func isPalindrome(x int) bool {
	if x < 0 {
		return false
	}
	xx := x
	y := 0
	for x != 0 {
		y = x%10 + y*10
		x = x / 10
	}
	if y == xx {
		return true
	} else {
		return false
	}
}

// ----------------------

func main() {
	fmt.Println(isPalindrome(123123123123123))
	fmt.Println(isPalindrome(922337203))
	fmt.Println(isPalindrome(-123))
	fmt.Println(isPalindrome(12521))
	fmt.Println(isPalindrome(125521))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant