Parsing user entered int into digits not working C++

59 Views Asked by At
vector<int> vec(unsigned int n)
{     
  vector<int> num;
  while (n != 0)
  {
    num.push_back(n%10);
    vec(n / 10);
  }
  return num;
}

This is a function to parse a user entered int into digits. I'm making a recursive call to the function which returns a vector. I check till the value of the number becomes zero. But when I run it, it's entering into a infinite loop.

What can be the problem?

2

There are 2 best solutions below

0
On

You basically have 2 loops right there 1 because of the recursivity and one because of the while.

The recursive call is correct but you should not put the condition into a while. There's where the infinite looping appears. In the while you are checking for n to be != 0, but n is not modified in that body. You should have:

if (n != 0)
{
num.push....
vec(n/10);
}
return num;
0
On

In your code, you are not storing the value of your recursive call, at line vec(n/10). And if you are doing recursion, there is no need to put while loop. You have to do only one : either recursion or loop.

Here is the code you might want to try :

Loop :

vector<int> vec(unsigned int n)
{
    vector<int> ans;
    while(n!=0)
    {
        ans.push_back(n%10);
        n=n/10;
    }
    reverse(ans.begin(),ans.end());
    return ans;
}

Here you need to reverse the vector to get in correct order (left to right).

Or you can try recursive way :

vector<int> vec1(unsigned int n)
{
    vector<int> ans;
    if(n==0)
        return ans;
    ans.push_back(n%10);
    vector<int> tmp=vec1(n/10);
    ans.insert(ans.end(),tmp.begin(),tmp.end());
    return ans;
}

And to still you need to reverse that so, your vec function should call this vec1 function :

vector<int> vec(unsigned n)
{
    vector<int> ans=vec1(n);
    reverse(ans.begin(),ans.end());
    return ans;
}