Created
December 12, 2012 15:01
-
-
Save anonymous/4268440 to your computer and use it in GitHub Desktop.
Revisions
-
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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; } }