Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✅7. 整数反转 #64

Open
bazinga-web opened this issue Jul 19, 2020 · 2 comments
Open

✅7. 整数反转 #64

bazinga-web opened this issue Jul 19, 2020 · 2 comments
Labels

Comments

@bazinga-web
Copy link

7. 整数反转

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:

输入: 123
输出: 321

 示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231,  231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

@bazinga-web
Copy link
Author

解法一:

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {
    const border = 2**31
    const max = border - 1
    const min = -border

    const result = (x > 0 ? 1 : -1) * String(x).split('').filter(x => x !== '-').reverse().join('')
    return result > max || result < min ? 0 : result 
};

解法二:

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {
    var max = Math.pow(2, 31) - 1;
    var min = -Math.pow(2, 31);
    var y = 0;
    while(x !== 0) {
        y = 10 * y + x % 10;
        x = ~~(x/10);
    }
    if (y > max) return 0;
    if (y < min) return 0;
    return y;
};

@Ray-56
Copy link
Owner

Ray-56 commented Jul 20, 2020

保存是否为负数,转字符串,排序,再依据保存的是否为负数的状态转回数值

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {
    var overflow = function(x) {
        return x >= Math.pow(2, 31) - 1 || x <= -Math.pow(2, 31) ? 0 : x;
    }
    var isNegative = x < 0;
    var arr = (isNegative ? -x : x).toString().split('');
    arr.reverse();
    var res = parseInt(arr.join(''));
    res = isNegative ? -res : res;
    res = overflow(res);
    return res;
};

@Ray-56 Ray-56 added the 简单 label Jul 20, 2020
@Ray-56 Ray-56 changed the title 7. 整数反转 ✅7. 整数反转 Jul 20, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants