Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split an int into its digits?

Tags:

c++

How can I split an int in c++ to its single numbers? For example, I'd like to split 23 to 2 and 3.

like image 796
ewggwegw Avatar asked Nov 23 '10 22:11

ewggwegw


People also ask

How do you separate numbers into digits in Excel?

This section will show a formula to split selected number cells into individual digits in Excel. 1. Select a blank cell (says cell C1) for locating the first split digit of number in cell A1, then enter formula =MID($A1,COLUMN()-(COLUMN($C1)- 1),1) into the formula bar, and then press the Enter key.

How do you divide a number into 2 digits?

int i = 45; // or anything you want int firstDigit = i / 10; int secondDigit = i % 10; It's quite simple really.

How do you extract digits from a number?

Extracting digits of a number is very simple. When you divide a number by 10, the remainder is the digit in the unit's place. You got your digit, now if you perform integer division on the number by 10, it will truncate the number by removing the digit you just extracted.


2 Answers

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.

like image 163
icecrime Avatar answered Sep 30 '22 15:09

icecrime


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 } 
like image 36
Svisstack Avatar answered Sep 30 '22 15:09

Svisstack