Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Determining beautiful number string in JavaScript
A numeric string, str, is called a beautiful string if it can be split into a sequence arr of two or more positive integers, satisfying the following conditions −
arr[i] - arr[i - 1] = 1, for any i in the index of sequence, i.e., each element in the sequence is more than the previous element.
No element of the sequence should contain a leading zero. For example, we can split '50607' into the sequence [5, 06, 07], but it is not beautiful because 06 and 07 have leading zeros.
The contents of the sequence cannot be rearranged.
For example −
If the input string is −
const str = '91011';
Then the output should be −
const output = true;
because the desired sequence is [9, 10, 11];
Example
The code for this will be −
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));
Output
And the output in the console will be −
true
Advertisements