Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - how to find the length of an integer

Tags:

I'm trying to find a way to find the length of an integer (number of digits) and then place it in an integer array. The assignment also calls for doing this without the use of classes from the STL, although the program spec does say we can use "common C libraries" (gonna ask my professor if I can use cmath, because I'm assuming log10(num) + 1 is the easiest way, but I was wondering if there was another way).

Ah, and this doesn't have to handle negative numbers. Solely non-negative numbers.

I'm attempting to create a variant "MyInt" class that can handle a wider range of values using a dynamic array. Any tips would be appreciated! Thanks!

like image 651
user1888527 Avatar asked Mar 26 '14 00:03

user1888527


People also ask

How do you find the length of an int in C?

int num; scanf("%d",&num); char testing[100]; sprintf(testing,"%d",num); int length = strlen(testing); Alternatively, you can do this mathematically using the log10 function.

How do you find the length of an integer?

Perhaps the easiest way of getting the number of digits in an Integer is by converting it to String, and calling the length() method. This will return the length of the String representation of our number: int length = String. valueOf(number).

What is the length of integer?

The length of an integer field is defined in terms of number of digits; it can be 3, 5, 10, or 20 digits long. A 3-digit field takes up 1 byte of storage; a 5-digit field takes up 2 bytes of storage; a 10-digit field takes up 4 bytes; a 20-digit field takes up 8 bytes.


1 Answers

The number of digits of an integer n in any base is trivially obtained by dividing until you're done:

unsigned int number_of_digits = 0;  do {      ++number_of_digits;       n /= base; } while (n); 
like image 80
Kerrek SB Avatar answered Oct 11 '22 20:10

Kerrek SB