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 整数反转 #2

Closed
sailei1 opened this issue May 16, 2019 · 0 comments
Closed

7 整数反转 #2

sailei1 opened this issue May 16, 2019 · 0 comments

Comments

@sailei1
Copy link
Owner

sailei1 commented May 16, 2019

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

示例 1:

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

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

输入: 120
输出: 21
注意:

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

解法
//1先判断 正负数
2然后字符串反转
3 再转数值 判断是否越界

var reverse = function(x) {
    let rs='';
    
    if(x<0){
        rs='-'
    }
   
    let str= (Math.abs(x)+'').replace(/\0/g, '');
     rs+= str.split('').reverse().join('');
    if( Number(rs)<Math.pow(-2, 31)||Number(rs)>Math.pow(2, 31)-1){
          rs=0;
    }

    return rs;
};
@sailei1 sailei1 closed this as completed May 17, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant