How can I split an int in c++ to its single numbers? For example, I'd like to split 23 to 2 and 3.
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.
int i = 45; // or anything you want int firstDigit = i / 10; int secondDigit = i % 10; It's quite simple really.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With