JS实现回文判断


三种方法实现回文判断的方法,运行时间依次减少

 1 /***********************************第一版**********************************************/
 2 //整数转换为字符串-->数组-->数组反转-->字符串,然后进行比较
 3 var isPalindrome = function(x) {
 4     if (x < 0) {
 5         return false;
 6     }else if (x >= 0 && x <= 9) {
 7         return true;
 8     }
 9     let b = x.toString();
10     let a = b.split("").reverse().join("");
11 
12     if (a === b) {
13         return true;
14     }else{
15         return false;
16     }
17 };
18 console.log(isPalindrome(121));
19 
20 
21 /***********************************第二版**********************************************/
22 //定义两个指针,一个从前开始,一个从后开始,一起往中间走,相遇为止。
23 //如果发现不一样的直接返回false,否则返回true
24 var isPalindrome = function(x) {
25     if (x < 0) {
26         return false;
27     }else if (x >= 0 && x <= 9) {
28         return true;
29     }
30     let arr = x.toString().split("");
31     
32     let left = 0,
33         right = arr.length-1;
34     while (left <= right) {
35         if (arr[left] !== arr[right]) {
36             return false;
37         }
38         left++;
39         right--;
40     }
41     return true;
42 };
43 let a = isPalindrome(10);
44 console.log(a);
45 
46 
47 /***********************************第三版**********************************************/
48 //运用数学的方法,先定义一个装结果的容器为sum为0.
49 //假如每次循环,该整数x取余的值为a,然后我们让sum每次乘10,再加上a,最后比较结果
50 var isPalindrome = function(x) {
51     if (x < 0) return false
52     let temp = x
53     let sum = 0
54     while (temp) {
55         sum = temp % 10 + sum * 10
56         temp = Math.floor(temp / 10)
57     }
58     if (sum === x) return true
59     return false
60 };
61 let a = isPalindrome(10);
62 console.log(a);

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM