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

前端 未结 10 1158
被撕碎了的回忆
被撕碎了的回忆 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

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

    #include 
    
    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 $ 
    

提交回复
热议问题