LeetCode算法題——翻轉整數

題目

在這裏插入圖片描述

思路:

每次獲取目標整數個位數,再每次乘以10加上最後餘數達到翻轉

tip:
% : 取餘
/ : 取整

代碼:

    public static int convert(int target) {
        int result = 0;
        if (target > Integer.MAX_VALUE || target < Integer.MIN_VALUE) {
            return 0;
        }
        while (target != 0) {
            result = result * 10 + target % 10;
            target = target / 10;
            if (result > Integer.MAX_VALUE / 10 || result < Integer.MIN_VALUE / 10) {
                return 0;
            }
        }
        return result;
    }

結果:

在這裏插入圖片描述

詳解:

1、入參target = 321
2、結果初始值 result = 0
3、第一次循環、321%10 = 1 result = 1 target = 321/10 = 32 個位獲取結束
4、第二次循環、32%10 = 2 result = 12 target = 32/10 = 3 獲取除了個位數1的數即32的個位數,加上之前的個位數乘以10爲結果最新值
5、第三次循環、3%10 = 3 result = 123 target = 3/10 = 0 同上
6、target !=0 條件不成立跳出循環,返回最終結果

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