leetCode演算法題:7.整數反轉
阿新 • • 發佈:2020-12-14
給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉。
示例1:
輸入: 123
輸出: 321
示例 2:
輸入: -123
輸出: -321
示例 3:
輸入: 120
輸出: 21
注意:
假設我們的環境只能儲存得下 32 位的有符號整數,則其數值範圍為[−231,231− 1]。請根據這個假設,如果反轉後整數溢位那麼就返回 0。
package com.panghl.leetcode.simple; import java.util.Scanner; /** * @Author panghl * @Date 2020/12/9 15:10 * @Description 整數反轉 **/ public class IntegerReverse { public static Integer input() { Scanner scanner = new Scanner(System.in); Integer nums = scanner.nextInt(); return nums; } public static void main(String[] args) { Integer num = input(); int reverse = reverse(num); System.out.println(reverse); } public static int reverse(int num) { //記錄反轉數字 int ans = 0; while (num != 0) { //記錄個位數 int pop = num % 10; //用於判斷反轉後的數字是否溢位 if (ans > Integer.MAX_VALUE/10 || ( ans == Integer.MAX_VALUE/10 && pop > 7)) { return 0; } if (ans < Integer.MIN_VALUE/10 || ( ans == Integer.MIN_VALUE/10 && pop < -8)) { return 0; } ans = ans * 10 + pop; num /= 10 ; } return ans; } }