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

但是溢出会抛出异常。
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;
    }
}

你可能感兴趣的:(java的漫长学习之路)