题目描述

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

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

GoLang 语法:if 判断

  1. if 判断的一般形式
if condition1 {
    // do something 
} else if condition2 {
    // do something else    
} else {
    // catch-all or default
}

(1)关键字 if 和 else 之后的左大括号 { 必须和关键字在同一行
(2)如果你使用了 else-if 结构,则前段代码块的右大括号 } 必须和 else-if 关键字在同一行

  1. 带有初始语句的 if 判断
if initialization; condition {
    // do something
}

(1)在初始化语句后方必须加上分号

AC 代码

func reverse(x int) int {
    ret := 0
    
    for x != 0{
        // if 判断语句
        if ret * 10 + x % 10 > ((1<<31)-1) || ret * 10 + x % 10 < (-(1<<31)){
            return 0
        }
        
        ret = ret * 10 + x % 10
        x /= 10
    }
    return ret
}
Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐