zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]Reverse Integer

    Reverse Integer 

    Reverse digits of an integer.

    Example1: x = 123, return 321
    Example2: x = -123, return -321

    click to show spoilers.

    Have you thought about this?

    Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

    If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

    Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

    For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

    https://leetcode.com/problems/reverse-integer/


    倒转数字,超过了2^31返回0。

     1 /**
     2  * @param {number} x
     3  * @return {number}
     4  */
     5 var reverse = function(x) {
     6     var sign = 1, res = 0, base = 1;
     7     if(x < 0){
     8         sign = -1;
     9         x = -1 * x;
    10     }
    11     x = x + "";
    12     for(var i = 0; i < x.length; i++){
    13         res += base * parseInt(x[i]);
    14         base *= 10;
    15     }
    16     if(res > Math.pow(2,31)){
    17         return 0;
    18     }
    19     return sign * res;
    20 };
  • 相关阅读:
    I/O模型
    同步异步与协程
    GIL(全局解释器锁)
    解决pycharm启动慢
    操作系统发展史
    TCP和UDP
    粘包问题
    网络编程
    异常
    常用函数汇总
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4769970.html
Copyright © 2011-2022 走看看