難度:簡單
題目:
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 Solution {
public int reverse(int x) {
if(x>0&&x<10) //只有一個正數的時候直接回傳
return x;
long reverse = 0; //題目會給 int溢出的大小數值
while(x!=0){ //x>0 and x<0 都要執行 所以就是 !=0
reverse*=10; //把原本已存的數值*10留位子給尾數
reverse += x%10; //加上尾數
x/=10; //x要除10
}
if(reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE)
return 0; //溢位要直接回傳0
return (int)reverse; //要強制轉型
}
}
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記