Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the digits of a number without converting it to a string/ char array?

Tags:

c++

How do I get what the digits of a number are in C++ without converting it to strings or character arrays?

like image 942
chustar Avatar asked Sep 09 '09 05:09

chustar


People also ask

How do you extract digits of a number and store it in an array?

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.

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.

How do you turn a number into a character?

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.


2 Answers

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); 
like image 81
Vinay Sajip Avatar answered Sep 22 '22 04:09

Vinay Sajip


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).

like image 28
tunnuz Avatar answered Sep 22 '22 04:09

tunnuz