在 JavaScript 中確定美麗的數字字串
如果數字字串 str 可以被分割成一個包含兩個或以上的正整數的序列 arr,並且滿足以下條件,則稱其為美麗的字串 −
對於序列中的任何索引 i,arr[i] - arr[i - 1] = 1,即序列中的每個元素都大於前一個元素。
序列中的任何元素都不應包含前導零。例如,我們可以將“50607”分割成序列 [5, 06, 07],但它不是美麗的,因為 06 和 07 存在前導零。
該序列中的內容不能重新排列。
例如 −
如果輸入字串是 −
const str = '91011';
則輸出應該是 −
const output = true;
因為所需的序列是 [9, 10, 11];
示例
程式碼如下 −
const str = '91011';
const isBeautiful = (str) => {
let i = 1;
let count=0;
const { length } = str;
while(i <= length / 2){
let check = true;
let j = i;
let left = BigInt(str.substring(0,j));
let nextRange = (left + 1n).toString().length;
while(j + nextRange <= length){
let right=BigInt(str.substring(j,j+nextRange));
if(left === right-1n){
left=right;
j+=nextRange;
nextRange=(left+1n).toString().length;
count=j;
}else{
check=false;
break;
}
};
if(check === true && count === length){
return true;
}
i++;
};
return false;
};
console.log(isBeautiful(str));輸出
控制檯中的輸出如下 −
true
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C #
MongoDB
MySQL
Javascript
PHP