leetcode 7

7. Reverse Integer

  • Total Accepted: 152273
  • Total Submissions: 640718
  • Difficulty: Easy

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321



思路:使用使用循環左移的思想,再移動期間判斷是否溢出。


public class Solution {
    public int reverse(int x) {
        int res = 0;
        
        while(x != 0){
            int tail = x%10;
            int next = res*10 + tail;
            if((next-tail)/10 != res){
                return 0;
            }
            res = next;
            x = x/10;
        }
        return res;
                
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章