# Three complete solutions

### Scheme 1

1) code:

``````/ / plan 1
var reverse = function(x) {
// 1) First use flag to save the positive and negative cases of x, x into a string xStr (without positive and negative signs, pure value), initialize resValue to 0, etc
const flag = x < 0 ? -1 : 1,
xStr = (x < 0 ? Math.abs(x) : x) + ' ',
l = xStr.length;
let index = 0,
resValue = 0;

// 2) When index < l,
// Process: resValue += parseInt(xStr[index]) * math.pow (10, index); index++;
while (index < l) {
const indexNum = parseInt(xStr[index]),
weight = Math.pow(10, index);

resValue += indexNum * weight;
index++;
}

// 3) Restore the symbol, and return different values according to the resValue situation
resValue *= flag;
// Boundary: if resValue is not [−231, 231 − 1], 0 must be returned
if (resValue < Math.pow(-2.31) || resValue > Math.pow(2.31) - 1) {
resValue = 0;
}

return resValue;
};
Copy the code``````

### Scheme 2

1) code:

``````// Option 2 is an "optimized version" of Option 1, which reduces the amount of code through various functions, tricks, etc
var reverse = function(x) {
const xStr = (x < 0 ? Math.abs(x) : x) + ' ',
flag = x < 0 ? -1 : 1;

let resValue = xStr.split(' ').reduce((acc, cur, index) = > {
// The following two rows can be merged into
// return acc += parseInt(cur) * Math.pow(10, index);
acc += parseInt(cur) * Math.pow(10, index);
return acc;
}, 0);

// Restore the symbol
resValue *= flag;

/ / the following three lines can be merged into the return (resValue < math.h pow (2, 31) | | resValue > math.h pow (2, 31) - 1)? 0 : resValue;
if (resValue < Math.pow(-2.31) || resValue > Math.pow(2.31) - 1) {
resValue = 0;
}

return resValue;
}
Copy the code``````

### 3 solution 3

1) code:

``````// Option 3 is also an "optimized" version of Option 1, with various functions, tricks, etc
var reverse = function(x) {
const flag = x > 0 ? 1 : -1,
reverseValue = (Math.abs(x) + ' ').split(' ').reverse().join(' ');

if (parseInt(reverseValue) < Math.pow(-2.31) | |parseInt(reverseValue) > Math.pow(2.31) - 1) {
return 0;
}

return reverseValue * flag;
}
Copy the code``````