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