- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpalindrome-number.ts
82 lines (73 loc) · 1.94 KB
/
palindrome-number.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* @description 求 1-10000 之间的回文数
* @author tangc1
* @date 2022-05-04 22:20:02
*/
/**
* @description 反转
* param {number} max
* return {array} []
*/
exportfunctionfindPalindromeNumber1(max: number): number[]{
constres: number[]=[]
if(max<=0)returnres
for(leti=1;i<=max;i++){
// 先转换成字符串,再转成数组,然后反转 比较
conststr=i.toString()
if(str===str.split('').reverse().join('')){
res.push(i)
}
}
returnres
}
/**
* @description 求 1 - max 之间的所有对称数(字符串前后比较)
* param {Object}
* return {Object}
*/
exportfunctionfindPalindromeNumber2(max: number): number[]{
constres: number[]=[]
if(max<=0)returnres
for(leti=1;i<=max;i++){
conststr=i.toString()
constlength=str.length
// 字符串头尾比较
letflag=true
letstartIndex=0
letendIndex=length-1
while(startIndex<endIndex){
if(str[startIndex]!==str[endIndex]){
flag=false
break;
}else{
startIndex++
endIndex--
}
}
if(flag)res.push(i)
}
returnres
}
/**
* @description 求 1 - max 之间的所有对称数(反转数字)
* param {Object}
* return {Object}
*/
exportfunctionfindPalindromeNumber3(max: number): number[]{
constres: number[]=[]
if(max<=0)returnres
for(leti=1;i<=max;i++){
letn=i;
letrev=0// 存储反转数
// 生成反转数字
while(n>0){
rev=rev*10+n%10
n=Math.floor(n/10)
}
if(i===rev)res.push(i)
}
returnres
}
// console.info(findPalindromeNumber1(1000));
// console.info(findPalindromeNumber2(1000));
// console.info(findPalindromeNumber3(1000));