Skip to content

Commit 98c3625

Browse files
authored
Update reverse_integer.md
1 parent 15fb143 commit 98c3625

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

reverse_integer.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
整数反转
33
## Problem
44
Given a 32-bit signed integer, reverse digits of an integer.
5+
## 分析
6+
注意题目为32个字节整型,因此最终返回为long int
57
## Approach1
68
将整型转化为字符型数组处理
79
### 代码实现
@@ -31,5 +33,27 @@ int reverse(int x)
3133
return 0;
3234
return (int)result*sign;
3335
}
36+
```
3437
## Approach2
38+
利用除法和mod运算
3539
### 代码实现
40+
```ruby
41+
int reverse(int x) {
42+
int sign;
43+
if(x>0)
44+
sign=1;
45+
else{
46+
sign=-1;
47+
x=abs(x);
48+
}
49+
long result=0;
50+
while(x>0)
51+
{
52+
result=result*10+x%10;
53+
x=x/10;
54+
}
55+
if(result>2147483647)
56+
return 0;
57+
return result*sign;
58+
}
59+
```

0 commit comments

Comments
 (0)