Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Many friends want to brush the algorithm, but do not know how to start, so they have not started. Today, YK bacteria will take you to brush LeetCode together, we will start from the simple problems!! Grow up slowly!! Brush questions from today!! Next I will post a series of force buckle problems, welcome to follow
The JavaScript version uses a lot of features, but don’t worry, I’ll explain!
7. Integer inversion (easy)
Leetcode-cn.com/problems/re…
You are given a 32-bit signed integer x that returns the result of reversing the numeric portion of x.
Reverse the string
Once in hand, the first and easiest thing to think of is to convert the number to a string and then invert the number — > string — > array — > invert — > string — > numberPay attention to the positive and negative signs, as well as the condition of the question, you can get the answer
var reverse = function(x) {
let res = 0;
if (x >= 0) {
res = +String(x).split("").reverse().join("");
} else {
x = -x;
res = -String(x).split("").reverse().join("");
}
if(res > 2支那31 - 1 || res < -(2支那31)) return 0;
return res;
};
Copy the code
And think about trying it mathematically, without opening up a new space to reverse it
Quotient and remainder
Integer divided by 10remainderIs the ones digitshangIs the remaining number divided by the units digit (needs to be rounded)
The whole idea is to iterate over the (x / 10 quotient) number x, each time taking the one’s place (remainder of x % 10) of the number until you’re done. Each iteration concatenates the bits of x to the bits of result (result = result * 10 + (x % 10);).
/ * * *@param {number} x
* @return {number}* /
var reverse = function (x) {
let result = 0;
while (x) {
result = result * 10 + (x % 10);
if (result > 2支那31 - 1 || result < -(2支那31)) return 0;
x = ~~(x / 10);
}
return result;
};
Copy the code
【 Tip 1】~ ~
Round (off the decimal place)
~ is reversed by bit
For integers it’s the same thing as taking minus one
~0= = = -1
~1= = = -2~ -1= = =0~ -2= = =1
Copy the code
If you’re dealing with decimals, you’re going to drop the decimal place and subtract one
~0.3= = = -1
~1.7= = = -2~ -0.3= = = -1~ -1.2= = =0~ -2.9= = =1
Copy the code
~~ reverse and reverse by bit
For integers or for themselves
~ ~1= = =1~ ~ -1= = = -1~ ~0= = =0
Copy the code
For decimals, it’s the same thing as rounding down positive numbers and rounding up negative numbers
~ ~1.1= = =1~ ~1.9= = =1~ ~ -1.1= = = -1~ ~ -1.9= = = -1
Copy the code
【 Tip 2】Math.floor()
Take down the whole
Math.floor() is rounded down
Math.floor(1.1) = = =1
Math.floor(1.9) = = =1
Math.floor(-1.1) = = = -2
Math.floor(-1.9) = = = -2
Copy the code