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

血红的双手。 提交于 2019-11-28 09:09:16
Kerrek SB

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

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

std::to_string(num).length()

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 size of the int:

ceil(8*sizeof(int) * log10(2))

EDIT:

For the number of decimal digits of some value:

ceil(log10(var+1))

This works for numbers > 0. Zero must be checked separately.

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

There is a much better way to do it

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

works for int and decimal

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;

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

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.
    */

Plain and pretty simple function

int intlen(int i)
    {
    int j=1;
    while(i>10){i=i/10;j++;}
    return j;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!