Reverse Integer 旋转数字

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

本地注意正负号判断比较关键,实现部分可能不是最优的,按照自己的想法实现:

设ret = 1;每次对x进行取余mod,然后ret = ret*10+mod;(第一次让ret = mod),最后返回ret

代码如下:

 1 public class Solution {
 2     public int reverse(int x) {
 3         int result = 0;
 4         int flag = (x < 0) ? 1 : 0;
 5         
 6         x = (x < 0) ? -x : x;
 7         
 8         int first = 1;
 9         while(x!=0){
10             int mod = x%10;
11             if(first == 1){
12                 result = mod;
13                 first = 0;
14             }else{
15                 result *= 10;
16                 result += mod;
17             }
18             
19             x /= 10;
20             
21         }
22         
23         return (flag == 1) ? -result : result;
24         
25     }
26 }
原文地址:https://www.cnblogs.com/fanchangfa/p/4041621.html