Question

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!

Was it helpful?

Solution 2

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

OTHER TIPS

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

std::to_string(num).length()

There is a much better way to do it

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

works for int and decimal

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

"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

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.

int intLength(int i) {
    int l=0;
    for(;i;i/=10) l++;
    return l==0 ? 1 : l;
}

Here's a tiny efficient one

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

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

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

How about (works also for 0 and negatives):

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

Best way is to find using log, it works always

int len = ceil(log10(num))+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.
    */

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

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

You can also use this function:

int countlength(int number)
{
    static int count = 0;
    if (number > 0)
    {
        count++;
        number /= 10;
        countlength(number);
    }
    return count;
}
#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));
}

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top