title: count the total number of 1's in integers from 1 to N
body: <p><strong>Problem Statement:</strong></p>
  
  <p>Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.</p>
  
  <p>For example:
  Given n = 13,
  Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.</p>
  
  <p><strong>Efficient Solution:</strong></p>
  
  <pre><code>int countDigitOne(int n) {
      if (n &lt;= 0) return 0;
      int q = n, x = 1, ans = 0;
      do {
          int digit = q % 10;
          q /= 10;
          ans += q * x;
          if (digit == 1) ans += n % x + 1;
          if (digit &gt;  1) ans += x;
          x *= 10;
      } while (q &gt; 0);
      return ans;
  }
  </code></pre>
  
  <p><strong>My question:</strong></p>
  
  <p>I found the solution to the question in one of the forums, I am finding it hard to comprehend the solution. I understand its a very simple one but please help me by explaining in detail. </p>
  
  <p>Thank you</p>