A simple article

7. Integer inversion

Train of thought

  1. Reverse: manually reverse values using the REVERSE method or of the JS array
  2. Interval: Use the match-pow function to get the NTH power value
  3. Negative number: the absolute value is used to calculate in the reverse process, and the negative sign is manually added to determine whether the original value is less than 0

Code implementation

function reverse(x: number): Number {// math.abs (x) = // -> toString().split('') = // -> reverse().join() = const temp = Math.abs(x).toString().split('').reverse().join('') let result = Number(temp) if (x < 0) {result = -result} // two intersections const min = -math.pow (2, 31) const Max = math.pow (2, 31) Return min <= result && result <= Max? result : 0 };Copy the code

9. A palindrome

Train of thought

  1. Converts numeric values to strings
  2. Finding the midIndex splits the string into two equally divided groups of length
  3. MidIndex determine:midIndex = len / 2Because of the whole down, for odd numbers it is accurate to find the median subscript, and for even numbers it is -1
  • Odd numbers: 5/2 = 2 => [1,2,3,4,5] midpoint subscript 2 => midpoint 3

Slice (0, midIndex),slice(midIndex+1, Length),slice(midIndex+1, length),slice(midIndex+1, length)

  • Even numbers: 4/2 = 2 => [1,2,3,4] Midpoint subscript [2-1,2] = [midIndex-1,midIndex] => middle value 2,3

[0,midIndex-1],[midIndex, length] code implementation is slice(0, midIndex),slice(midIndex, length),slice closed before open

Code implementation

function isPalindrome(x: number): boolean {
    const strArr = x.toString().split('')
    const numStrLen = strArr.length

    if (numStrLen === 1) return true
    if (numStrLen === 2) return strArr[0] === strArr[1]

    const midIndex = numStrLen / 2
    const str1 = strArr.slice(0, midIndex)
    const str2 = strArr.slice(numStrLen % 2 ? midIndex + 1 : midIndex, numStrLen)
    
    return str1.join('') === str2.reverse().join('')
};
Copy the code