c++ - Count the digits -


here's question:

take integer n (n >= 0) , digit d (0 <= d <= 9) integer. square numbers k (0 <= k <= n) between 0 , n. count numbers of digits d used in writing of k**2. call nb_dig (or nbdig or ...) function taking n , d parameters , returning count.

but output 1 less expected. can tell missing:

expected: equal 4700

actual: 4699

class countdig {   public:   static int nbdig(int n, int d)   {     if(n==0 && d==0)       return 0;      int c = 0;      for(int = 0;i<=n;i++)     {       int p=i*i;       while(p)       {         int l;         l=p%10;         if(l==d)           c++;         p=p/10;       }     }      return c;   } }; 

you dont count first 0 (0*0), because loop condition p (while(p)).

so add condition add 1 c, if p 0 , d zero

class countdig { public: static int nbdig(int n, int d) {     int c=0;     if (d==0)          c=1; // start 1, when counting 0    for(int i=1;i<=n;i++)   {       int p=i*i;       while(p)      {         int l;         l=p%10;          if(l==d)             c++;         p=p/10;      }    } return c; } }; 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -