-
-
Save gakuzzzz/4268485 to your computer and use it in GitHub Desktop.
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 characters
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