Skip to content
New issue

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

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

Already on GitHub? # to your account

第七题 - 整数反转 #8

Open
laizimo opened this issue May 25, 2020 · 0 comments
Open

第七题 - 整数反转 #8

laizimo opened this issue May 25, 2020 · 0 comments

Comments

@laizimo
Copy link
Owner

laizimo commented May 25, 2020

题目描述

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

示例 1:
输入: 123
输出: 321

示例 2:
输入: -123
输出: -321

示例 3:
输入: 120
输出: 21

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

算法

数组方法

答案

/**
 * 通过数组反转方法
 */
var reverse = function(x) {
    //#1 把x绝对值,转成字符串,分割,反转,合并
    let res = parseInt(Math.abs(x).toString().split('').reverse().join(''));

    //#2 判断溢出
    if (res.toString(2).length >= 32) res = 0;

    return x > 0 ? res : -res;
};
@laizimo laizimo changed the title 第七题 - 第七题 - 整数反转 May 25, 2020
# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

1 participant