# 判断回文数
Example 1:
| 输入:target = 12321 |
| 输出:true |
| 解释:12321 反过来也是12321 |
Example 2:
| 输入:target = '12321' |
| 输出:true |
| 解释:可以输入字符串类型,那么'12321' 反过来也是 '12321' |
Example 3:
| 输入:target = 123456 |
| 输出:false |
| 解释:123456 反过来是 654321 |
# Solving Ideas
# method 1
| function isPalindromic(target) { |
| target = String(target) |
| let length = target.length - 1 |
| for (let i = 0; i < target.length; i++) |
| if((target[i] != target[length--])) return false |
| return true |
| } |
# method 2
- 尽量不转换为字符串来解题
- 但本质上
replace
也会转换为字符串
| function isPalindromic(target) { |
| const hash = {} |
| target.__proto__.replace = ''.replace |
| target.replace(/\d/ig, (item, i,c) => {hash[i] = +item, hash['length'] = i + 1}) |
| const values = Object.values(hash) |
| return values.every((_, i) => hash[i] === values[--hash['length']]) |
| } |
# method 3
- 一行代码搞定
- 转换字符串再转换为数组进行翻转再进行连接比较
| const isPalindromic = target => String(target).split('').reverse().reduce((current, item) => current + item) == target |
# method 4
| const isPalindromic = target => Number(String(target).split('').reverse().join('')) == target |
# method 5
| function isPalindromic(target) { |
| let stack = [] |
| while (target > 0) { |
| stack.push(target % 10) |
| target = ~~(target / 10) |
| } |
| let length = stack.length |
| for (let i = 0; i < stack.length; i++) |
| if(stack[i] != stack[--length]) return false |
| return true |
| } |
# 测试的代码
| console.log(isPalindromic(12321)) |
| console.log(isPalindromic('123321')) |
| console.log(isPalindromic(123)) |