Leetcode 7

Problem Description
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.

Java:

class Solution {
    public int reverse(int x) {
        if (x == Integer.MIN_VALUE) return 0;
        int flag = x > 0 ? 1 : -1;
        x *= flag;
        int res = 0;
        
        while (x != 0) {
            if ((Integer.MAX_VALUE - x%10)/10 < res) return 0;
            res = res*10 + x%10;
            x /= 10;
        }
        
        return res * flag;
    }
}
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 智商決定你的下限 情商決定你的上限 你說話讓人舒服的程度 能決定你所能抵達的高度
    我的鑰匙閱讀 232評論 0 0
  • 午后陽光尚好,驅走早起時的寒風。我叫了一杯紅豆沙冰,坐在咖啡廳靠窗的椅子上。老板把刨冰機故意弄得咯吱作響,似乎不滿...
    葡萄籽加石榴閱讀 598評論 1 1

友情鏈接更多精彩內(nèi)容