ReverseInteger:實現int整數的反轉


原文鏈接

Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

class Solution1 {
    public int reverse(int x) {
        while (x % 10 == 0) {
            x /= 10;
        }
        boolean tag = false;
        if (x < 0) {
            tag = true;
            x = x * -1;
        }
        String s = String.valueOf(x);
        char[] ch = s.toCharArray();
        for (int i = 0;i < ch.length;i++) {
            int k = ch.length - i - 1;
            if (k < ch.length / 2) break;
            char cc = ch[i];
            ch[i] = ch[k];
            ch[k] = cc;
        }
        String re = String.valueOf(ch);
        int RI = Integer.valueOf(re);
        if (tag) RI = RI * -1;
        System.out.println(RI);
        return RI;
    }
}
/*
* 1. 前幾天剛做了字符反轉的,想當然就以為可以直接拿來用。結果卻和出題人意圖相差甚遠.Solution1的方案對於小部分的測試數據可行,但是當前的狀態是行不通的,也沒有繼續對此進行修改完善.
* 2. 一開始做的時候下面的Solution思路類似,但是因為對算法的邏輯思路不是很透徹,寫出來的代碼肯定很雜亂繁瑣。下面的這個解題思路有參考到Discussion中的一個答案.
* 3. 昨晚做出來之后一直不曉得哪里出錯了,沒有意識到int類型的邊界范圍,還特別納悶為啥斷點跟蹤的時候1534236469這個數字最后一下子就變了.根本沒有考慮過怎么處理"int類型數據溢出"問題
*   上網搜索了一下之后才曉得怎么判斷int類型問題。https://www.cnblogs.com/hesiyi/p/6963435.html
*
* */
class Solution {
    public int reverse(int x) {
        int sum = 0;
        int t = 0;
        while (x != 0) {
            if ((sum * 10L) > Integer.MAX_VALUE || (sum * 10L) < Integer.MIN_VALUE)
                return 0;
            sum = sum * 10 + x % 10;
            x = x / 10;
        }
        return sum;
    }
}
public class ReverseInteger {
    public static void main(String[] args) {
        Solution1 solu = new Solution1();
        int kkk = solu.reverse(-214748364); // -2147483648,1534236469
        System.out.println(kkk);
    }
}

關於int類型數據溢出的問題,移步博客:java-int數據的溢出


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM