Reverse digits of an integer.git
Example1: x = 123, return 321
Example2: x = -123, return -321spa
本地注意正負號判斷比較關鍵,實現部分可能不是最優的,按照本身的想法實現:code
設ret = 1;每次對x進行取餘mod,而後ret = ret*10+mod;(第一次讓ret = mod),最後返回retblog
代碼以下:it
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 }