在 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