Skip to content

Instantly share code, notes, and snippets.

@hishidama
Created August 8, 2012 16:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hishidama/3296651 to your computer and use it in GitHub Desktop.
Save hishidama/3296651 to your computer and use it in GitHub Desktop.
ビット演算を駆使したFizzBuzz
package jp.hishidama.joke;
public class FizzBuzz {
public static void main(String[] args) {
for (String s : args) {
System.out.println(new FizzBuzz(s));
}
}
public static final String FIZZ = "Fizz";
public static final String BUZZ = "Buzz";
private String s;
public FizzBuzz(String s) {
this.s = s;
}
@Override
public String toString() {
int b = fizz(s) | buzz(s);
int r = b ^ 3;
int n = (r & 1) * FIZZ.length() + ((r >> 1) & r) * BUZZ.length();
int l = ((r >> 1) & r) * s.length() + (b & 1) * FIZZ.length()
+ (b >> 1) * BUZZ.length();
return (FIZZ + BUZZ + s).substring(n, n + l);
}
int fizz(String s) {
// Java7だとswitchでStringが指定できるので、このif文も削れる
if (s.length() == 1) {
switch (s.charAt(0)) {
case '0':
case '3':
case '6':
case '9':
return 1;
default:
return 0;
}
}
int n = 0;
for (char c : s.toCharArray()) {
n += c - '0';
}
return fizz(String.valueOf(n));
}
int buzz(String s) {
switch (s.charAt(s.length() - 1)) {
case '0':
case '5':
return 2;
default:
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment