32

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!

5
  • 1
    @KerrekSB Actually I think he means the total unsigned value. That would be 2 to the power of ( sizeof( int ) * 8 - 1 ), right? EDIT: Nevermind. Commented Mar 26, 2014 at 0:16
  • 3
    The number of digits in a decimal integer is (log(number) / log(10)). Commented Mar 26, 2014 at 0:16
  • 1
    Don't reinvent the wheel, use a "Big Number" Library. Search the web for "c++ big number library". Commented Mar 26, 2014 at 0:20
  • 1
    int len = n?0:1; while (n) { len++, n/=10 } Commented Mar 26, 2014 at 0:24
  • 1
    Thanks for the tip, Thomas, but this is actually an assignment for class, and a little bit of a programming challenge for a newbie! Commented Mar 26, 2014 at 0:26

17 Answers 17

43

Not necessarily the most efficient, but one of the shortest and most readable using C++:

std::to_string(num).length() 
Sign up to request clarification or add additional context in comments.

1 Comment

and this solution meets this requirement. It additionally handle negative numbers. xD
39

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

3 Comments

There is no reason to use this solution as log10-based solutions are much better.
@tleb: better in what sense? Have you compared the two approaches?
Like this better than the log10 solution but would prefer a more explicit while (n != 0) for readability. Still, worth an upvote.
31

There is a much better way to do it

 #include<cmath> ... int size = trunc(log10(num)) + 1 .... 

works for int and decimal

UPDATE 27/07/2023

we can use this line to check for negatives and 0 values.

int size = num == 0 ? 1 : (num < 0 ? static_cast<int>(log10(std::abs(num))) + 1 : static_cast<int>(log10(num)) + 1); 

3 Comments

I like this (hence the upvote), just unfortunate it doesn't work for the number zero ...
I agree this is a really good answer and deserves the upvote. If your use case does not expect or has safeguards against zero, this is the best solution.
But when num==0 you have a problem. log10(0) is undefined
10

If you can use C libraries then one method would be to use sprintf, e.g.

#include <cstdio> char s[32]; int len = sprintf(s, "%d", i); 

2 Comments

You could use snprintf(nullptr, 0, "%d", i);` and not need s.
This also will not work for 128-bit integers. The nullptr solution from @Tony will fix that.
9

"I mean the number of digits in an integer, i.e. "123" has a length of 3"

int i = 123; // the "length" of 0 is 1: int len = 1; // and for numbers greater than 0: if (i > 0) { // we count how many times it can be divided by 10: // (how many times we can cut off the last digit until we end up with 0) for (len = 0; i > 0; len++) { i = i / 10; } } // and that's our "length": std::cout << len; 

outputs 3

Comments

4

Closed formula for the longest int (I used int here, but works for any signed integral type):

1 + (int) ceil((8*sizeof(int)-1) * log10(2)) 

Explanation:

 sizeof(int) // number bytes in int 8*sizeof(int) // number of binary digits (bits) 8*sizeof(int)-1 // discount one bit for the negatives (8*sizeof(int)-1) * log10(2) // convert to decimal, because: // 1 bit == log10(2) decimal digits (int) ceil((8*sizeof(int)-1) * log10(2)) // round up to whole digits 1 + (int) ceil((8*sizeof(int)-1) * log10(2)) // make room for the minus sign 

For an int type of 4 bytes, the result is 11. An example of 4 bytes int with 11 decimal digits is: "-2147483648".

If you want the number of decimal digits of some int value, you can use the following function:

unsigned base10_size(int value) { if(value == 0) { return 1u; } unsigned ret; double dval; if(value > 0) { ret = 0; dval = value; } else { // Make room for the minus sign, and proceed as if positive. ret = 1; dval = -double(value); } ret += ceil(log10(dval+1.0)); return ret; } 

I tested this function for the whole range of int in g++ 9.3.0 for x86-64.

3 Comments

ceil(log10(var+1)) will fail for INT_MAX
This is not reliable, the max value of type will fail. Totally agree with bricklore. I prefer std::to_string(num).length() as Riot said.
The problem of INT_MAX was fixed by converting to double before adding 1.
3
int intLength(int i) { int l=0; for(;i;i/=10) l++; return l==0 ? 1 : l; } 

Here's a tiny efficient one

1 Comment

you have to save the case i == 0. which is also 1 and current function returns 0;
2

Being a computer nerd and not a maths nerd I'd do:

char buffer[64]; int len = sprintf(buffer, "%d", theNum); 

1 Comment

Which will crash spectacularly when 256-bit integers become available :-)
2

Would this be an efficient approach? Converting to a string and finding the length property?

int num = 123 string strNum = to_string(num); // 123 becomes "123" int length = strNum.length(); // length = 3 char array[3]; // or whatever you want to do with the length 

1 Comment

Not very efficient though.
2

How about (works also for 0 and negatives):

int digits( int x ) { return ( (bool) x * (int) log10( abs( x ) ) + 1 ); } 

Comments

2

Best way is to find using log, it works always

int len = ceil(log10(num))+1; 

3 Comments

For num==50, log10(50) ~= 1.7, ceil(1.7) = 2 plus 1 gives 3. Rounding up with ceil is the wrong approach.
You should truncate instead of rounding up
what about zero: => log10(0) is undefined?
1

Code for finding Length of int and decimal number:

#include<iostream> #include<cmath> using namespace std; int main() { int len,num; cin >> num; len = log10(num) + 1; cout << len << endl; return 0; } //sample input output /*45566 5 Process returned 0 (0x0) execution time : 3.292 s Press any key to continue. */ 

Comments

0

There are no inbuilt functions in C/C++ nor in STL for finding length of integer but there are few ways by which it can found
Here is a sample C++ code to find the length of an integer, it can be written in a function for reuse.

#include<iostream> using namespace std; int main() { long long int n; cin>>n; unsigned long int integer_length = 0; while(n>0) { integer_length++; n = n/10; } cout<<integer_length<<endl; return 0; } 

Here is another way, convert the integer to string and find the length, it accomplishes same with a single line:

#include<iostream> #include<cstring> using namespace std; int main() { long long int n; cin>>n; unsigned long int integer_length = 0; // convert to string integer_length = to_string(n).length(); cout<<integer_length<<endl; return 0; } 

Note: Do include the cstring header file

Comments

0

The easiest way to use without any libraries in c++ is

#include <iostream> using namespace std; int main() { int num, length = 0; cin >> num; while(num){ num /= 10; length++; } cout << length; } 

1 Comment

This does not really add anything new to what other answers (including the accepted one) have proposed.
0

You can also use this function:

int countlength(int number) { static int count = 0; if (number > 0) { count++; number /= 10; countlength(number); } return count; } 

1 Comment

Please don't post the same answer to multiple questions.
0
#include <math.h> int intLen(int num) { if (num == 0 || num == 1) return 1; else if(num < 0) return ceil(log10(num * -1))+1; else return ceil(log10(num)); } 

1 Comment

Check your boundary values. intLen(10) returns 1.
-2

Most efficient code to find length of a number.. counts zeros as well, note "n" is the number to be given.

#include <iostream> using namespace std; int main() { int n,len= 0; cin>>n; while(n!=0) { len++; n=n/10; } cout<<len<<endl; return 0; } 

2 Comments

This provides nothing that the accepted answer does not provide.
Yes. 14 answers already and this isn't any different to many of them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.