本文思路參考:git
做者:青貓123
來源:CSDN
原文:https://blog.csdn.net/superstar987/article/details/80426102
算法
整數反轉題目:主要是要反轉整數+判斷溢出this
Given a 32-bit signed integer, reverse digits of an integer.spa
Example 1:.net
Input: 123 Output: 321
Example 2:code
Input: -123 Output: -321
Example 3:blog
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.it
這道題的要求是要反轉整數,可是若是反轉事後溢出的話,就要返回0;重點在於如何判斷是否溢出。io
Answer:function
class Solution { public static int reverse(int num){ { int length = 0; //給出數的長度 int rev = 0; if(num >= 0) length = (num+"").length(); else length = (num+"").length(); //負數會佔用一位符號位 for(int i = 0; i < length; i++) { int temp = num % 10; //取最後一位數 num = (num - temp) / 10; //把最後一位拋掉之後獲得的新的數 rev += temp*Math.pow(10, length - i -1); //反轉數 } if(rev > Math.pow(2, 32) - 1 || rev < (-1) * Math.pow(2, 31)) //判斷溢出,簡單暴力 return 0; return rev; } } }
public int reverse(int x) { long result = 0; while (x != 0) { result = result * 10 + x % 10; x /= 10; //算法比上一種更加簡單 } if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) //Integer.MAX_VALUE就是232 result = 0; return (int)result; }