7. 整数反转

难度: 简单




方法一: 转为字符串,将字符串反转后再转为整型

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
func reverse(x int) int {
if x == 0 || x < -2147483648 || x > 2147483647 {
return 0
}

if x > 0 {

rs := dealPostiveData(x)

if rs < -2147483648 || rs > 2147483647 {
return 0
} else {
return rs
}

} else {
numPostive := x * -1
rsPostive := dealPostiveData(numPostive)

rs := rsPostive * -1

if rs < -2147483648 || rs > 2147483647 {
return 0
} else {
return rs
}
}
}


func dealPostiveData(num int) (int) {

var sli []string
numStr := strconv.Itoa(num)
for _, v := range numStr {
sli = append(sli, string(v))
}

long := len(sli)

var sli2 []string
for k := range sli {
sli2 = append(sli2, sli[long-k-1])
}

rsStr := ""

for _, val := range sli2 {
rsStr += val
}

rs, _ := strconv.Atoi(rsStr)
return rs

}


方法二: 除10取余