Skip to content

Instantly share code, notes, and snippets.

Created December 12, 2012 15:01
Show Gist options
  • Save anonymous/4268440 to your computer and use it in GitHub Desktop.
Save anonymous/4268440 to your computer and use it in GitHub Desktop.

Revisions

  1. @invalid-email-address Anonymous created this gist Dec 12, 2012.
    43 changes: 43 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    public class OnesFunction {

    private static LoadingCache<Integer, Integer> cache = CacheBuilder
    .newBuilder().maximumSize(1000)
    .expireAfterAccess(10, TimeUnit.MINUTES)
    .build(new CacheLoader<Integer, Integer>() {
    @Override
    public Integer load(final Integer i) throws ExecutionException {
    return countOnes(i);
    }
    });

    /**
    * @param args
    * @throws ExecutionException
    */
    public static void main(String[] args) throws ExecutionException {
    int i = 2;
    while (true) {
    final int n = countOnes(i);
    System.out.println("" + i + ":" + n);
    if (i == n)
    break;
    i++;
    }
    }

    public static int countOnes(final int i) throws ExecutionException {
    if (i == 0)
    return 0;
    return internalCountOnes(i) + cache.get(i - 1);
    }

    private static int internalCountOnes(final int i) {
    final String s = String.valueOf(i);
    int sum = 0;
    for (final char c : s.toCharArray())
    if (c == '1')
    sum += 1;
    return sum;
    }

    }