LeetCode每日一练
Revese Interger
/*
 * @Author: fox
 * @Date: 2022-04-23 07:09:48
 * @LastEditors: fox
 * @LastEditTime: 2022-04-23 08:33:19
 * @Description: https://leetcode.com/problems/reverse-integer/
 */
/**
 * @description: 大神写的
 * @param {number} x
 * @return {number}
 */
const minInt = - (2 ** 31)
const maxInt = - minInt - 1
const reverse = (x) => {
    const flag = x < 0
    let res = 0
    // 1. 如果x为负数,将x转换为正数
    if (flag) {
        x = -x
    }
    // 2. 翻转数字,依次从末尾将数字赋值给临时数字
    while (x > 0) {
        const remainder = x % 10
        res  = res * 10 + remainder // 重点:这个语句不仅重新赋值,还可以将为0的开始数字清除掉
        x = Math.floor(x / 10)
    }
    // 3. 返回结果越界计算
    if (res > maxInt) { return 0 }
    return flag ? -res: res
}
/**
 * @description: 自己写的,将数字转换成字符串再转换成数组,然后再翻转数组,进行一系列判断之后,再转换回数字输出
 * @param {number} x
 * @return {number}
*/
// const reverse = (x) => {
//     let arr = []
//     let flag
//     let res = 0
//     if ((-2) ** 31 > x || x > 2 ** 31 - 1) return 0
//     arr = (`${x}`).split('')
//     console.log(arr)
    
//     if (arr[0] === '-') {
//         flag = arr.splice(0, 1)
//     }
//     for (const _ in arr) {
//         if (arr[_] === '0') {
//             arr.splice(0, 1)
//         } else {
//             break
//         }
//     }
//     res = flag? Number(`-${arr.reverse().join('')}`) : Number(arr.reverse().join(''))
//     if ((-2) ** 31 > res || res > 2 ** 31 - 1) return 0
//     return res
// };