Reverse Integer

一 問題描述

Reverse Integer

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.
翻譯:
給定一串32位的有符號整數,將這個整數顛倒。假定運行環境最多隻能支持32位的整數,並且假定如果溢出函數返回0。

二 解法

1. 第一解法(個人)

思路:
在js中,array對象有一個reverse方法用於顛倒數組。Math.pow(x, y)計算x的y次方,用於驗證是否溢出。
代碼:

var reverse = function(x) {
    
    let flag = x > 0;
    let str = x.toString().split("").reverse().join("");
    var num = parseInt(str);
    if(num > Math.pow(2, 31)){
        return 0;
    }
    return flag ? num : -num;
};

結果:

1032 / 1032 test cases passed.
Status: Accepted
Runtime: 76 ms
Memory Usage: 35.8 MB

By DoubleJan
2019.7.6

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