How can I count the digits in an integer without a string cast?

前端 未结 10 1137
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 00:54

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 m

相关标签:
10条回答
  • 2020-12-03 01:36
    int length = (int)Math.Log10(Math.Abs(number)) + 1;
    

    You may need to account for the negative sign..

    0 讨论(0)
  • 2020-12-03 01:36

    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 $ 
    
    0 讨论(0)
  • 2020-12-03 01:43

    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++;
    }
    
    0 讨论(0)
  • 2020-12-03 01:45

    You can use a while loop, which will likely be faster than a logarithm because this uses integer arithmetic only:

    int len = 0;
    while (n > 0) {
        len++;
        n /= 10;
    }
    

    I leave it as an exercise for the reader to adjust this algorithm to handle zero and negative numbers.

    0 讨论(0)
提交回复
热议问题