最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C++實現(xiàn)LeetCode(7.翻轉(zhuǎn)整數(shù))

 更新時間:2021年07月09日 17:10:11   作者:Grandyang  
這篇文章主要介紹了C++實現(xiàn)LeetCode(7.翻轉(zhuǎn)整數(shù)),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下

[LeetCode] 7. Reverse Integer 翻轉(zhuǎn)整數(shù)

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.

翻轉(zhuǎn)數(shù)字問題需要注意的就是溢出問題,看了許多網(wǎng)上的解法,由于之前的 OJ 沒有對溢出進行測試,所以網(wǎng)上很多人的解法沒有處理溢出問題也能通過 OJ。現(xiàn)在 OJ 更新了溢出測試,所以還是要考慮到。為什么會存在溢出問題呢,由于int型的數(shù)值范圍是 -2147483648~2147483647, 那么如果要翻轉(zhuǎn) 1000000009 這個在范圍內(nèi)的數(shù)得到 9000000001,而翻轉(zhuǎn)后的數(shù)就超過了范圍。博主最開始的想法是,用 long 型數(shù)據(jù),其數(shù)值范圍為 -9223372036854775808~9223372036854775807, 遠大于 int 型這樣就不會出現(xiàn)溢出問題。但實際上 OJ 給出的官方解答并不需要使用 long,一看比自己的寫的更精簡一些,它沒有特意處理正負號,仔細一想,果然正負號不影響計算,而且沒有用 long 型數(shù)據(jù),感覺寫的更好一些,那么就貼出來吧:

解法一:

class Solution {
public:
    int reverse(int x) {
        int res = 0;
        while (x != 0) {
            if (abs(res) > INT_MAX / 10) return 0;
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }
};

在貼出答案的同時,OJ 還提了一個問題 To check for overflow/underflow, we could check if ret > 214748364 or ret < –214748364 before multiplying by 10. On the other hand, we do not need to check if ret == 214748364, why? (214748364 即為 INT_MAX / 10

為什么不用 check 是否等于 214748364 呢,因為輸入的x也是一個整型數(shù),所以x的范圍也應(yīng)該在 -2147483648~2147483647 之間,那么x的第一位只能是1或者2,翻轉(zhuǎn)之后 res 的最后一位只能是1或2,所以 res 只能是 2147483641 或 2147483642 都在 int 的范圍內(nèi)。但是它們對應(yīng)的x為 1463847412 和 2463847412,后者超出了數(shù)值范圍。所以當(dāng)過程中 res 等于 214748364 時, 輸入的x只能為 1463847412, 翻轉(zhuǎn)后的結(jié)果為 2147483641,都在正確的范圍內(nèi),所以不用 check。

我們也可以用 long 型變量保存計算結(jié)果,最后返回的時候判斷是否在 int 返回內(nèi),但其實題目中說了只能存整型的變量,所以這種方法就只能當(dāng)個思路擴展了,參見代碼如下:

解法二:

class Solution {
public:
    int reverse(int x) {
        long res = 0;
        while (x != 0) {
            res = 10 * res + x % 10;
            x /= 10;
        }
        return (res > INT_MAX || res < INT_MIN) ? 0 : res;
    }
};

到此這篇關(guān)于C++實現(xiàn)LeetCode(7.翻轉(zhuǎn)整數(shù))的文章就介紹到這了,更多相關(guān)C++實現(xiàn)翻轉(zhuǎn)整數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

大庆市| 常熟市| 安阳县| 镇江市| 玉山县| 澄江县| 神农架林区| 金溪县| 雅江县| 辉县市| 乌恰县| 昌乐县| 湾仔区| 新闻| 尤溪县| 葵青区| 阜康市| 玛曲县| 襄汾县| 泸溪县| 曲阜市| 南汇区| 西林县| 大丰市| 汉中市| 田林县| 滨海县| 和龙市| 电白县| 兴义市| 汝州市| 泰和县| 芜湖市| 桃园县| 罗源县| 崇左市| 那曲县| 永春县| 铁岭市| 鄂州市| 沐川县|