zlacker

[return to "My favorite programming problem to teach: Digit length (2019)"]
1. chacha+9c3[view] [source] 2024-06-06 06:07:28
>>equili+(OP)
Am I the only one who, in response to: "dont use loops" thought of the following:

   int numDigits(int num){
     if (num < 0){
       return numDigits(-1 * num);
     }
     if (num < 10){
       return 1;
     }
     if (num < 100){
       return 2;
     }
     if (num < 1000){
       return 3;
     }
     if (num < 10000){
       return 4;
     }
     if (num < 100000){
       return 5;
     }
     if (num < 1000000){
       return 6;
     }
     if (num < 10000000){
       return 7;
     }
     if (num < 100000000){
       return 8;
     }
     if (num < 1000000000){
       return 9;
     }
     return 10; // cant be more than 10 since sizeof(int) == 4, otherwise extend to 19
   }
◧◩
2. lelant+Ap3[view] [source] 2024-06-06 08:15:47
>>chacha+9c3
Might not work (I think Python supports bignums, not too sure).

I did this which will work with any length of number[1], and appears to work for all edge cases, including numbers that start with zero and doesn't use loops:

     (defun num-digits (n)
       (if (< n 10)
         1
         (+ 1 (num-digits (floor n 10)))))
[1] Millions of digits, if your computer has the RAM for it.
[go to top]