JavaScript 中的迴文數
我們需要編寫一個 JavaScript 函式來輸入一個數字,並確定它是否是迴文數。
迴文數 - 迴文數是指從左讀和從右讀都相同的數字。
例如 -
343 是迴文數
6789876 是迴文數
456764 不是迴文數
示例
程式碼如下 -
const num1 = 343;
const num2 = 6789876;
const num3 = 456764;
const isPalindrome = num => {
let length = Math.floor(Math.log(num) / Math.log(10) +1);
while(length > 0) {
let last = Math.abs(num − Math.floor(num/10)*10);
let first = Math.floor(num / Math.pow(10, length −1));
if(first != last){
return false;
};
num −= Math.pow(10, length−1) * first ;
num = Math.floor(num/10);
length −= 2;
};
return true;
};
console.log(isPalindrome(num1));
console.log(isPalindrome(num2));
console.log(isPalindrome(num3));輸出
在控制檯中的輸出將為 -
true true false
廣告
資料結構
網路
關係型資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C #
MongoDB
MySQL
JavaScript
PHP