We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
This C++ solution passes all test cases. The problem is actually really simple if you use the right approach.
First off don't try to 'seperate' the numbers as the title of the challenge suggests. Simply vary the size of the first element and concatenate to that 1 plus the integer representation of that element until the size of the string is the same as the original string. If at any point the two strings are equal then you are done and the string is beautiful.
#include <string>
#include <vector>
#include <iostream>
using namespace std;
bool isBeautiful(string str, long long int &firstElem) {
if (str[0]=='0') {
return false;
}
if (str.size()<=1) {
return false;
}
for (int i = 1; i <= str.size()/2; i++) {
string a = str.substr(0,i);
firstElem = stoll(a);
int diff = 1;
while (a.size() < str.size()) {
a += to_string(firstElem+(diff));
diff++;
}
if (a.compare(str)==0) {
return true;
}
}
return false;
}
int main()
{
int n;
cin >> n;
long long int firstElem = 0;
while (n-->0) {
string str;
cin >> str;
if (isBeautiful(str, firstElem)) {
cout << "YES " << firstElem<<endl;
}
else {
cout << "NO"<<endl;
}
}
return 0;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Separate the Numbers
You are viewing a single comment's thread. Return to all comments →
This C++ solution passes all test cases. The problem is actually really simple if you use the right approach. First off don't try to 'seperate' the numbers as the title of the challenge suggests. Simply vary the size of the first element and concatenate to that 1 plus the integer representation of that element until the size of the string is the same as the original string. If at any point the two strings are equal then you are done and the string is beautiful.