文章目录
一、Fizz Buzz
public List<String> fizzBuzz(int n) {
List<String> list = new ArrayList<>(n);
for (int i = 1; i <= n ; i++) {
boolean b1 = i%3==0;
boolean b2 = i%5==0;
if(b1&&b2){
list.add("FizzBuzz");
}else if(b1){
list.add("Fizz");
}else if(b2){
list.add("Buzz");
}else{
list.add(""+i);
}
}
return list;
}
二、计数质数
public int countPrimes(int n) {
boolean[] arr = new boolean[n];
int cnt = 0;
for(int i = 2; i < n; i++) {
if(arr[i]) continue;
cnt++;
for(int j = i; j < n; j+=i) {
arr[j] = true;
}
}
return cnt;
}
三、3的幂
public boolean isPowerOfThree(int n) {
if (n > 1){
while (n % 3 == 0){
n /= 3;
}
}
return n == 1;
}
四、罗马数字转整数
public int romanToInt(String s) {
Map<String,Integer> map = new HashMap<>();
map.put("I",1);
map.put("IV",4);
map.put("V",5);
map.put("IX",9);
map.put("X",10);
map.put("XL",40);
map.put("L",50);
map.put("XC",90);
map.put("C",100);
map.put("CD",400);
map.put("D",500);
map.put("CM",900);
map.put("M",1000);
if(map.containsKey(s)){
return map.get(s);
}else{
StringBuilder sb = new StringBuilder();
int num = 0;
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
if(!map.containsKey(sb.toString()+chars[i])){
if(sb.length()>0){
num += map.get(sb.toString());
sb = new StringBuilder();
i--;
}
}else{
sb.append(chars[i]);
}
}
if(sb.length()>0){
num += map.get(sb.toString());
}
return num;
}
}