对称数
求 1 - 10000 之间的所有对称数(回文)
例如:0,1,2,11,22,101,232,1221....
思路1:使用数组反转
- 数字转换为字符串
- 字符串转换为数组 reverse ,再 join 生成字符串
- 比较前后的字符串
/**
* 查询 1-max 的所有对称数(数组反转)
* @param max 最大值
*/
export function findPalindromeNumbers1(max: number): number[] {
const res: number[] = []
if (max <= 0) return res
for (let i = 1; i <= max; i++) {
// 转换为字符串,转换为数组,再反转,比较
const s = i.toString()
if (s === s.split('').reverse().join('')) {
res.push(i)
}
}
return res
}
思路2:使用字符串头尾比较
- 数字转换为字符串
- 字符串头尾比较
还可以使用**栈**(但栈会用到数组,性能不如直接操作字符串)
- 数字转换为字符串,求长度
- 如果长度是偶数,则用栈比较
- 如果长度是奇数,则忽略中间的数字,其他的用栈比较
/