In this Separate the Numbers HackerRank solution, A numeric string, , is beautiful if it can be split into a sequence of two or more positive integers, , satisfying the following conditions:
- for any (i.e., each element in the sequence is more than the previous element).
- No contains a leading zero. For example, we can split into the sequence , but it is not beautiful because and have leading zeroes.
- The contents of the sequence cannot be rearranged. For example, we can split into the sequence , but it is not beautiful because it breaks our first constraint (i.e., ).
The diagram below depicts some beautiful strings:
Perform queries where each query consists of some integer string . For each query, print whether or not the string is beautiful on a new line. If it is beautiful, print YES x
, where is the first number of the increasing sequence. If there are multiple such values of , choose the smallest. Otherwise, print NO
.
Function Description
Complete the separateNumbers function in the editor below.
separateNumbers has the following parameter:
- s: an integer value represented as a string
Prints
– string: Print a string as described above. Return nothing.
Input Format
The first line contains an integer , the number of strings to evaluate.
Each of the next lines contains an integer string to query.
Constraints
Separate the Numbers HackerRank Solution
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in Python
def separateNumbers(s):
for i in range(len(s)//2):
starting_digit = int(s[:i+1])
new_s = s[:i+1]
if len(new_s)*2 <= len(s):
digit = starting_digit
while len(new_s) < len(s):
digit += 1
new_s += str(digit)
if (new_s == s):
print("YES", str(starting_digit))
return
print("NO")
Problem Solution in JavaScript
function separateNumbers(s) {
// Write your code here
for (let i = 1; i < s.length; i++) {
// use BigInt for test cases with large numbers
let curr = BigInt(s.slice(0, i));
let temp = curr.toString();
while (temp.length < s.length) {
curr++;
temp += curr.toString();
}
if (temp === s) {
return console.log(`YES ${ s.slice(0, i) }`);
}
}
return console.log("NO");
}
Leave a Reply