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.
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment