Problems caused by a simple question of leetcode

The following is a simple question on leetcode

The content of the question is to enter the number of -2^31 -2^31-1, find its inverse ordinal number, and return 0 if the inverse ordinal number overflows

The idea of ​​the algorithm is relatively simple, which is to use the input number, keep dividing by 10 to get the remainder, and then use the quotient as the dividend, and z keeps going until the quotient is 0.
But there are many points to pay attention to. This is only for the case of writing code in js. The division in js does not mean that it is divided. It is not like C/C++.

  (/) in c/c++

If the integer obtained by dividing a positive integer is an integer (quotient is rounded down), for example, 4/3 = 1
If the integer obtained by dividing a positive integer is an integer (quotient is rounded up) and for example-4/3 = -1
Here must be noted that the rounding method of positive and negative numbers is different. The principle is well understood.

 js(/)

js division will keep the decimal part, it will automatically determine whether the result is a decimal or a positive number, and will not
round off the result. Here, the js function Math.ceil() rounding up function and Math.floor() must be used here. Round down function

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {
    
    
    //除十取余法
    //需要注意如果是负数就需要s向上取整,正数是 向下取整
    var yushu = 0,shang = x;
    var number = 0;
    do{
    
    
        yushu = shang%10;
        if(shang>0) shang = Math.floor(shang/10);
        else shang = Math.ceil(shang/10);
        number = number*10+yushu;
    }while(shang!=0)
    //设置超出-2^31和2^31-1之间就返回0
    if(number>=2147483647||number<=-2147483648) return 0;
    return number;
};

Guess you like

Origin blog.csdn.net/qq_44606064/article/details/108920023