How do I split an int into its digits?
How can I split an int in c++ to its single numbers? For example, I'd like to split 23 to 2 and 3.
Given the number 12345 :
5
is 12345 % 10
4
is 12345 / 10 % 10
3
is 12345 / 100 % 10
2
is 12345 / 1000 % 10
1
is 12345 / 10000 % 10
I won't provide a complete code as this surely looks like homework, but I'm sure you get the pattern.
Reversed order digit extractor (eg. for 23 will be 3 and 2):
while (number > 0)
{
int digit = number%10;
number /= 10;
//print digit
}
Normal order digit extractor (eg. for 23 will be 2 and 3):
std::stack<int> sd;
while (number > 0)
{
int digit = number%10;
number /= 10;
sd.push(digit);
}
while (!sd.empty())
{
int digit = sd.top();
sd.pop();
//print digit
}
The following will do the trick
void splitNumber(std::list<int>& digits, int number) {
if (0 == number) {
digits.push_back(0);
} else {
while (number != 0) {
int last = number % 10;
digits.push_front(last);
number = (number - last) / 10;
}
}
}
A simple answer to this question can be:
- Read A Number "n" From The User.
- Using While Loop Make Sure Its Not Zero.
- Take modulus 10 Of The Number "n"..This Will Give You Its Last Digit.
- Then Divide The Number "n" By 10..This Removes The Last Digit of Number "n" since in int decimal part is omitted.
- Display Out The Number.
I Think It Will Help. I Used Simple Code Like:
#include <iostream>
using namespace std;
int main()
{int n,r;
cout<<"Enter Your Number:";
cin>>n;
while(n!=0)
{
r=n%10;
n=n/10;
cout<<r;
}
cout<<endl;
system("PAUSE");
return 0;
}