How do I get what the digits of a number are in C++ without converting it to strings or character arrays?
views:
626answers:
9Use a sequence of mod 10 and div 10 operations (whatever the syntax is in C++) to assign the digits one at a time to other variables.
In pseudocode
lsd = number mod 10
number = number div 10
next lsd = number mod 10
number = number div 10
etc...
painful! ... but no strings or character arrays.
First digit (least significant) = num % 10, second digit = floor(num/10)%10, 3rd digit = floor(num/100)%10. etc
Something like this:
int* GetDigits(int num, int * array, int len) {
for (int i = 0; i < len && num != 0; i++) {
array[i] = num % 10;
num /= 10;
}
}
The mod 10's will get you the digits. The div 10s will advance the number.
The following prints the digits in order of ascending significance (i.e. units, then tens, etc.):
if (n == 0)
puts("0");
else {
while (n > 0) {
int digit = n % 10;
printf("%d\n", digit);
n /= 10;
}
}
You want to some thing like this?
int n = 0;
std::cin>>n;
std::deque<int> digits;
if(n == 0)
{
digits.push_front(0);
return 0;
}
n = abs(n);
while(n > 0)
{
digits.push_front( n % 10);
n = n /10;
}
return 0;
Since everybody is chiming in without knowing the question.
Here is my attempt at futility:
#include <iostream>
template<int D> int getDigit(int val) {return getDigit<D-1>(val/10);}
template<> int getDigit<1>(int val) {return val % 10;}
int main()
{
std::cout << getDigit<5>(1234567) << "\n";
}
What about floor(log(number))+1?
With n digits and using base b you can express any number up to: pow(n,b)-1. So to get the number of digits of a number x in base b you can use the inverse function of exponentiation: base-b logarithm. To deal with non-integer results you can use the floor()+1 trick.
PS: This works for integers, not for numbers with decimal (in that case you should know what's the precision of the type you are using).
I have seen many answers, but they all forgot to use do {...} while()
loop, which is actually the canonical way to solve this problem and handle 0
properly.
My solution is based on this one by Naveen.
int n = 0;
std::cin>>n;
std::deque<int> digits;
n = abs(n);
do {
digits.push_front( n % 10);
n /= 10;
} while (n>0);
Not as cool as Martin York's answer, but addressing just an arbitrary a problem:
You can print a positive integer greater than zero rather simply with recursion:
#include <stdio.h>
void print(int x)
{
if (x>0) {
print(x/10);
putchar(x%10 + '0');
}
}
This will print out the least significant digit last.