1. 程式人生 > >LeetCode演算法題:JAVA實現整數反轉reverse integer

LeetCode演算法題:JAVA實現整數反轉reverse integer

題目來源:LeetCode
Reverse digits of an integer.

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

1、首先我想到的是最笨的方法
思路:將整數轉為陣列,通過陣列的角標來實現反轉,再將陣列最終轉為int型別(陣列–>String–>Integer)

class Solution {
    public int reverse(int x){
         char[] arrs = Integer.toString(x).toCharArray();
            char
temp=0; if(x>0){ int z=0,y=arrs.length-1; while(z < arrs.length/2){ temp = arrs[z]; arrs[z] = arrs[y]; arrs[y] = temp; z++; y--; } } else{ int
z=1,y=arrs.length-1; while(z <= (arrs.length-1)/2){ temp = arrs[z]; arrs[z] = arrs[y]; arrs[y] = temp; z++; y--; } } StringBuilder sb = new StringBuilder(); for
(int i=0;i<arrs.length;i++){ sb.append(arrs[i]); } int res = 0; try{ res = Integer.parseInt(sb.toString()); }catch(Exception e){ } return res; } }

但是溢位會丟擲異常。
2、模十取餘
不斷模10取得最低位,再不斷乘10相加得到最終的反轉結果

public class Solution {
    public int reverseInteger(int x) {
        int res = 0; 
        while (x != 0) {
            int temp = res * 10 + x % 10;
            x = x / 10; //不斷取前幾位
            if (temp / 10 != res) {
                res = 0;
                break;
            }
            res = temp;
        }
        return res;
    }
}