find the “string length” of an int

前端 未结 6 1914
情话喂你
情话喂你 2020-12-31 21:13

basically I want to return the number of digits in the int -> values like this:

(int)1 => 1
(int)123 => 3
(int)12345678 => 8

I kno

6条回答
  •  猫巷女王i
    2020-12-31 21:32

    Probably much faster than using log or int-to-string conversion and without using any library functions is this:

    int nDigits(int i)
    {
      if (i < 0) i = -i;
      if (i <         10) return 1;
      if (i <        100) return 2;
      if (i <       1000) return 3;
      if (i <      10000) return 4;
      if (i <     100000) return 5;
      if (i <    1000000) return 6;      
      if (i <   10000000) return 7;
      if (i <  100000000) return 8;
      if (i < 1000000000) return 9;
      return 10;
    }
    

    EDIT after Jeff Yates concerns:

    For those who worry about int sizes different from 32-bits (similar to pmg's solution but still faster because multiplication is faster than division :-)

    #include 
    
    #define PO10_LIMIT (INT_MAX/10)
    
    
    int nDigits(int i)
    {
      int n,po10;
    
      if (i < 0) i = -i;
      n=1;
      po10=10;
      while(i>=po10)
      {
        n++;
        if (po10 > PO10_LIMIT) break;
        po10*=10;
      }
      return n;
    }
    

提交回复
热议问题