English: leetcode.com/problems/re…

English: leetcode-cn.com/problems/re…

Topic describes

Given a 32 – bit signed integer, you need to invert each digit of the integer.

Example 1:

Input: 123 Output: 321Copy the code

Example 2:

Input: -123 Output: -321Copy the code

Example 3:

Input: 120 Output: 21Copy the code

Note:

Assuming that our environment can store only 32-bit signed integers, the value range is [−.– 1). Based on this assumption, return 0 if the integer overflows after inversion.

Answer key

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {// convert the number to a string, and then convert the string to an array."123"- > ["1"."2"."3"] / / - 123 - >"123"- > ["-"."1"."2"."3"]
    let arr = x.toString().split(' '); // Check if there is a negative signif(arr[0] ! = ="-"{/ / /"1"."2"."3"] - > ["3"."2"."1"] - >"321"-> 321 // If the original Number is 120, the use of Number() in this step will directly remove the 0let num = Number(arr.reverse().join(' '));
        if (num <= Math.pow(2, 31) && num >= -Math.pow(2, 31)) {
            return num;
        } else {
            return0; }}else if (arr[0] === "-") {
        delete arr[0];
        let num = Number(arr.reverse().join(' '));
        if(num < = math.h pow (2, 31) && num > = - Math. Pow (31), 2) {/ / take after, add 1return ~num + 1;
        } else {
            return0; }}};Copy the code

Reverse by bit?

The digit 1 is reversed: ~1

The binary value of 1 is 00000001

After the bit is reversed: 11111110

Complete by reversing the bits, and then convert the binary to decimal

When we convert to decimal, we find that the sign bit (the highest bit) is 1, indicating that this is a negative number

Invert everything except the sign bit: 10000001

Add 1 to the last bit to get its complement: 10000010

Finally converted to decimal: -2

Negative binary to decimal?

Remove sign bit minus 1;

Remove sign bit, reverse bit; The result is a negative code;

The source code is converted to the corresponding decimal

Signed binary to decimal?

The initial value of 11110000

1: the value is bitwise reversed 00001111

2: Add 1 to the result of the previous step to generate the complement code 00010000

3: converted to decimal 16