How do I get what the digits of a number are in C++ without converting it to strings or character arrays?
Extract the last digit of the number N by N%10, and store that digit in an array(say arr[]). Update the value of N by N/10 and repeat the above step till N is not equals to 0. When all the digits have been extracted and stored, traverse the array from the end and print the digits stored in it.
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.
char a = Character. forDigit(num1, 10); We have used the forDigit() method converts the specified int value into char value. Here, 10 and 16 are radix values for decimal and hexadecimal numbers respectively.
The following prints the digits in order of ascending significance (i.e. units, then tens, etc.):
do { int digit = n % 10; putchar('0' + digit); n /= 10; } while (n > 0);
What about floor(log(number))+1
?
With n digits and using base b you can express any number up to pow(b,n)-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 decimals (in that case you should know what's the precision of the type you are using).
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