How can I count the digits in an integer without a

2019-01-11 02:41发布

I fear there's a simple and obvious answer to this question. I need to determine how many digits wide a count of items is, so that I can pad each item number with the minimum number of leading zeros required to maintain alignment. For example, I want no leading zeros if the total is < 10, 1 if it's between 10 and 99, etc.

One solution would be to cast the item count to a string and then count characters. Yuck! Is there a better way?

Edit: I would not have thought to use the common logarithm (I didn't know such a thing existed). So, not obvious - to me - but definitely simple.

标签: zero-pad
10条回答
聊天终结者
2楼-- · 2019-01-11 03:16

Since a number doesn't have leading zeroes, you're converting anyway to add them. I'm not sure why you're trying so hard to avoid it to find the length when the end result will have to be a string anyway.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-11 03:18

I would have posted a comment but my rep score won't grant me that distinction.

All I wanted to point out was that even though the Log(10) is a very elegant (read: very few lines of code) solution, it is probably the one most taxing on the processor.

I think jherico's answer is probably the most efficient solution and therefore should be rewarded as such.

Especially if you are going to be doing this for a lot of numbers..

查看更多
小情绪 Triste *
4楼-- · 2019-01-11 03:21

This should do it:

int length = (number ==0) ? 1 : (int)Math.log10(number) + 1;
查看更多
Anthone
5楼-- · 2019-01-11 03:21

Okay, I can't resist: use /=:

#include <stdio.h>

int
main(){
        int num = 423;
        int count = 1;
        while( num /= 10)
                count ++;
        printf("Count: %d\n", count);
        return 0;
}
534 $ gcc count.c && ./a.out
Count: 3
535 $ 
查看更多
我想做一个坏孩纸
6楼-- · 2019-01-11 03:23

One solution is provided by base 10 logarithm, a bit overkill.

查看更多
姐就是有狂的资本
7楼-- · 2019-01-11 03:23

You can loop through and delete by 10, count the number of times you loop;

int num = 423;
int minimum = 1;
while (num > 10) {
    num = num/10;
    minimum++;
}
查看更多
登录 后发表回答