LeetCode 7


### Description:

Given a 32-bit signed integer, reverse digits of an integer.

  • 题意:
    倒置int32的整数

  • 思路:
    如果每次取余的话其实不用考虑正负,要注意的是边界, 倒置后的数有可能overflows,具体看代码


Example:


  1. Input: 123
    Output: 321

  2. Input: -123
    Output: -321

  3. Input: 120
    Output: 21



代码


Golang

func reverse(x int) int {
	max := 1<<31 - 1
	min := -1 << 31
	y := 0
	for x != 0 {
		y = 10*y + x%10
		x /= 10
	}
	if y < min || y > max {
		return 0
	}
	return y
}

posted @ 2018-03-14 09:31  shengwudiyi  阅读(67)  评论(0编辑  收藏  举报