Counting digits using while loop

前端 未结 7 592
清酒与你
清酒与你 2021-01-05 10:15

I was recently making a program which needed to check the number of digits in a number inputted by the user. As a result I made the following code:

int x;            


        
7条回答
  •  [愿得一人]
    2021-01-05 10:41

    Given a very pipelined cpu with conditional moves, this example may be quicker:

    if (x > 100000000) { x /= 100000000; count += 8; }
    if (x > 10000) { x /= 10000; count += 4; }
    if (x > 100) { x /= 100; count += 2; }
    if (x > 10) { x /= 10; count += 1; }
    

    as it is fully unrolled. A good compiler may also unroll the while loop to a maximum of 10 iterations though.

提交回复
热议问题