C++ · Solution

Number to String

This C++ solution uses string processing for Number to String. Read the reasoning, inspect the code, or try your own test case below.

StringsString processingC++46 lines
Solution153of 248
Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

String processing

Number to String: scan the character sequence while maintaining the positions, counts, or partial match information required to construct the answer.

Strings

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

View exact source file ↗
Implementation

number_to_string.cpp

C++

    #include <bits/stdc++.h>
     
    using namespace std;
     
    int main(){
        ios::sync_with_stdio(0);
        cin.tie(0);
        string s;
        cin >> s;
        if (s.size() == 1 || s.find_first_not_of('0', 1) == -1) {
            cout << 0 << '\n';
            return 0;
        }
        int first = s[0] - '0' + 1;
        string want = to_string(first);
        for(int i = 0; i < s.length() - 1; i++){
            want.append("0");
        }
        int x = want.length(), y = s.length();
        vector<int> a(x), b(x, 0);
        for(int i = 0; i < x; i++){
            a[i] = want[x - 1 - i] - '0';
        }
        for(int i = 0; i < y; i++){
            b[i] = s[y - 1 - i] - '0';
        }
        for(int i = 0; i < x; i++){
            a[i] -= b[i];
            if (a[i] < 0) {
                a[i] += 10;
                a[i + 1]--;
            }
        }
        int pos = x - 1;
        //remove leading 0
        while(pos > 0 && a[pos] == 0){
            pos--;
        }
        string ans;
        while(pos >= 0){
            char temp = (char) (a[pos] + '0');
            ans.push_back(temp);
            pos--;
        }
        cout << ans << '\n';
    }   
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.