Separate the Numbers

  • + 0 comments

    c++

    void separateNumbers(string s) {
        long long number, next;
        string new_string;
        bool possible = false;
        // try to build the beautiful string starting with the first number, if it's not possible increase the number of digits and try again
        for (int digits = 1; digits <= s.size()/2; digits++) {
            // get the first number with the current number of digits from the string given
            // also keep the number for later to print if it's good
            number = stoll(s.substr (0, digits));
            // get the next number, for beautiful condition
            next = number + 1;
            // concatenate numbers with the next beautiful number until the minimum length is achieved
            new_string = s.substr(0, digits) + to_string(next);
            while (new_string.size() < s.size()) {
                next++;
                new_string += to_string(next);
            }
            // if the length is equal and the number is the same, it's possible
            if (new_string.size() == s.size() && new_string == s) {
                possible = true;
                // early exit, no need to continue checking
                break;
            }
        }
        // print result
        if (possible) {
            cout<<"YES "<<number<<endl;
        } else {
            cout<<"NO"<<endl;
        }
    }