Pages

Monday, June 29, 2015

Count 1's between numbers

Count how many 1's in range of numbers
ex: 1 to 20 equals to twelve 1's

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
^                         ^   ^ ^ ^   ^   ^   ^   ^   ^   ^   ^


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import java.util.*;

public class CountOne{
   public static void main(String[] args){  
      int n=20;
      long i = 0, j = 1;
      long count = 0;
      for (i = 1; i <= n; i ++)
      {
          j = i;
          while (j != 0)
          {
              if (j % 10 == 1)
                  count ++;
              j /= 10;
          }
      }
      System.out.print(count); 
   }
}

No comments:

Post a Comment