LeetCode第7題_Reverse Integer

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.



思路:先嘗試取到各個字的digit,在反序去進行打印

改寫為題目對應的函式



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public static int reverse(int x){
        ArrayList revRes = new ArrayList();
        int src = x;
        if(x<0){
            x = x*(-1);
        }
        while(x>0){
            int digit = x%10;
            revRes.add(digit);
            x/=10;
        }
        int res = Integer.parseInt(revRes.toString().replace("[", "").replace("]", "").replace(", ", ""));
        if(src<0){
            res = res * (-1);
            return res;
        }
        return res;
    }


要注意數值範圍越界溢位的問題

第二版.(過關版)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package leetcode7_reverseinteger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 *
 * @author chous
 */
public class LeetCode7_ReverseInteger {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        BufferedReader input;
        input = new BufferedReader(new InputStreamReader(System.in));
        //System.out.println("Integer.MAX:" + Integer.MAX_VALUE);
        //System.out.println("Integer.Min:" + Integer.MIN_VALUE);
        System.out.println("Input");
        String strInput = input.readLine();
        int numInput = Integer.parseInt(strInput);
        System.out.println(numInput);
        System.out.println(reverse(numInput));
    }
    
    public static int reverse(int x){
        int temp = 0;
        int result = 0;
        while (x != 0) {
            temp = result * 10 + x % 10;
            // 判断是否越界
            if(temp / 10 != result) {
                return 0;
            }
            x = x / 10;
            result = temp;
        }
        return result;
    }
    
}








留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題