Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split an Integer into its digits c++

Tags:

c++

I'm trying to learn c++ on my own and I've hit a bit of a road block. The problem is I need to take an integer,split it into its digits and get the sum of the digits and display them.

Example:

input number: 123456
digits in the integer: 1 2 3 4 5 6
sum: 21

I have it all done, but when I rip the integer, into digits I can't display it correctly. It displays in reverse order.

So in the program below I enter 1234 and it spits out 4 3 2 1. I know why, I just don't know how to fix it.

Here is my code so far:

#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <math.h>

int countDigitsInInteger(int n)
{
    int count =0;
    while(n>0)
    {
       count++;
       n=n/10;
    }
    return count;
}

using namespace std;

int main(int argc, char *argv[])
{  
    int intLength =0;
    int number;
    int digit;      
    int sum = 0;
    string s;    
    cout << "Please enter an integer ";
    cin >>number;
    cout << "Orginal Number = "<<number <<endl;
    //make the number positive
    if (number<0)
    number = -number;    
    intLength = countDigitsInInteger(number);
    //break apart the integer into digits
    while(number>0)
    {                         
        digit = number % 10;
        number = number / 10;        
        cout <<digit << " "; 
        sum = sum+digit; 
    } 
    cout <<endl <<"Sum of the digits is: "<<sum<<endl;
    system("PAUSE");
    return EXIT_SUCCESS;
}

Here is my solution

can't see :)

like image 679
nkuebelbeck Avatar asked Dec 01 '25 08:12

nkuebelbeck


2 Answers

Your problem comes from the fact that you are reading the digits backwards, thus you need to print them out backwards. A stack will help you tremendously.

#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <stack>

int countDigitsInInteger(int n)
{
    int count =0;
    while(n>0)
    {
        count++;
        n=n/10;
    }
    return count;
}

using namespace std;

int main(int argc, char *argv[])
{  
    int intLength =0;
    int number;
    int digit;      
    int sum = 0;
    string s;    
    cout << "Please enter an integer ";
    cin >>number;
    cout << "Orginal Number = "<<number <<endl;
    //make the number positive
    if (number<0)
        number = -number;    

    intLength = countDigitsInInteger(number);
    //break apart the integer into digits

    stack<int> digitstack;
    while(number>0)
    {                         
        digit = number % 10;
        number = number / 10;
        digitstack.push(digit);
        sum = sum+digit; 
    }

    while(digitstack.size() > 0)
    {
        cout << digitstack.top() << " ";
        digitstack.pop();
    }

    cout <<endl <<"Sum of the digits is: "<<sum<<endl;
    system("PAUSE");
    return EXIT_SUCCESS;
}

Oh, and BTW, keep your indentation clean. Its important.

EDIT: In response to Steve Townsend, this method is not necessarily overkill, it is just different from yours. The code can be slimmed down so that it seems less like overkill:

#include <iostream>
#include <stack>
#include <string>

using namespace std;

int getInput(string prompt)
{
    int val;
    cout << prompt;
    cin >> val;
    return val < 0 ? -val : val;
}

int main(int argc, char** argv)
{
    int num = getInput("Enter a number: ");
    cout << "Original Number: " << num << endl;

    stack<int> digits;
    int sum = 0;
    while(num > 0)
    {
        digits.push(num % 10);
        sum += digits.top();
        num = num / 10;
    }

    while(digits.size() > 0)
    {
        cout << digits.top() << " ";
        digits.pop();
    }

    cout << endl << "Sum of digits is " << sum << endl;

    return 0;
}
like image 162
riwalk Avatar answered Dec 03 '25 20:12

riwalk


Stack and recursion is overkill for this problem. Just store each digit into a string and then reverse it before output. You need to work out how to call reverse with the string members for this to work. for_each can be used to output each element of the string.

For extra credit (by virtue of conciseness and expressiveness), insert the number directly into an ostringstream and use that as the basis for your reversible string.

My stringstream version of this code is 5 lines long. Logic is:

  • declare stringstream
  • declare int with value
  • output int to stringstream
  • create string from stringstream
  • output the result digit by digit using for_each.

You can sum the digits using accumulate on the string, provide you account for the fact that int('1') != 1. That's an extra two lines, to sum the digits and output the result.

The point is not that doing this via stack or recursion is BAD, it's just that once you get more familiar with the STL there are typically more elegant ways to do a job than the obvious. Implementing this using stack, recursion and any other ways you can think of makes a simple homework into a great real-world learning experience.

Here's the accumulate code to sum the members of a string consisting of decimal digits, for example:

#include <string>
#include <numeric>

std::string intString("654321");
int sum = accumulate(intString.begin(), intString.end(), 0) - 
    (intString.size() * int('0'));

EDIT: here's the full code, for comparative purposes:

ostringstream intStream;
int value(123456);

intStream << value;

string intString(intStream.str());
for_each(intString.begin(), intString.end(), [] (char c) { cout << c << endl; });

int sum = accumulate(intString.begin(), intString.end(), 0) - 
        (intString.size() * int('0'));
cout << "Sum is " << sum << endl;
like image 42
Steve Townsend Avatar answered Dec 03 '25 22:12

Steve Townsend



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!