Chuỗi số gọi là "đẹp" nếu tách được thành dãy 2+ số nguyên dương thỏa: (1) số sau = số trước + 1, (2) không số nào có leading zero, (3) không sắp xếp lại.
Ví dụ: '91011' → true (dãy [9,10,11]).
Ví dụ
const str = '91011';
const isBeautiful = (str) => {
let i = 1;
const { length } = str;
while (i <= length / 2) {
let check = true, 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;
} else { check = false; break; }
}
if (check && j === length) return true;
i++;
}
return false;
};
console.log(isBeautiful(str));
Kết quả
true