Home > Back-end >  Convert an integer to an array of digits C
Convert an integer to an array of digits C

Time:05-02

Here is my code, I have the var numB and I want to add each element to the vector<int> res;. How would I do such a thing? Here is the problem statement:You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.

Increment the large integer by one and return the resulting array of digits.

#include <string>
#include <sstream>

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        vector<int> res;
        stringstream ss;
        for (int i : digits)
            ss << i;
        int numB;
        ss >> numB;
        numB  ;
    }
};

CodePudding user response:

If what you really want is just to get the resulting vector, you can do this with math instead of converting things to strings

std::vector<int> plusOne(const std::vector<int>& digits) {
    std::vector<int> res = digits;
    res[res.size()-1]  = 1;

    // carry the 1 if any digit is > 9
    int p = res.size()-1;
    while (res[p] > 9) {
        res[p] = res[p] % 10;
        if (p > 0) {
            res[p - 1]  = 1;
            --p;
        }
        else {
            res.insert(res.begin(), 1);
        }
    }

    return res;
}

You can try it out and see that it works, make sure to test with a number where the result has more digits than the input.

void print(const std::string& name, const std::vector<int>& v) {
    std::cout << name << " = ";
    for (auto&& vi : v) std::cout << vi << " ";
    std::cout << std::endl;
}

int main() {
    std::vector<int> in = { 1,2,9 };
    auto out = plusOne(in);
    print("in",in);
    print("out",out);

    in = {9,9 };
    out = plusOne(in);
    print("in",in);
    print("out",out);

    return 0;
}

Produces this result:

in = 1 2 9
out = 1 3 0
in = 9 9
out = 1 0 0

If you really want to do it with strings for some reason, this will accomplish the same thing

std::vector<int> plusOne(const std::vector<int>& digits) {
    std::vector<int> res;

    std::stringstream ss;
    for (int i : digits) {
        ss << i;
    }
    int numB;
    ss >> numB;
    numB  ;

    std::stringstream ss2;
    ss2 << numB;
    std::string ss2s = ss2.str();
    for (int i = 0; i < ss2s.size();   i) {
        std::string c = ss2s.substr(i, 1);
        res.push_back(std::atoi(c.c_str()));
    }
    
    return res;
}
  •  Tags:  
  • c
  • Related