9.Fizz Buzz
Given number n. Print number from 1 to n. But:
when number is divided by 3, print "fizz".
when number is divided by 5, print "buzz".when number is divided by both 3 and 5, print "fizz buzz".ExampleIf n = 15, you should return:
[
"1", "2", "fizz", "4", "buzz", "fizz", "7", "8", "fizz", "buzz", "11", "fizz", "13", "14", "fizz buzz"]Challenge
Can you do it with only one if statement?看了一些答案使用了多个if,这里给出几种方案给大家参考下
1、建立HashMap,将3,6,9,12,5,10,0(i%15==0)所对应的字符串分别映射,这样一个if(map.containsKey(i%15))即可public static HashMapmap = new HashMap<>(); static{ map.put(3,"fizz"); map.put(6,"fizz"); map.put(9,"fizz"); map.put(12,"fizz"); map.put(5,"buzz"); map.put(10,"buzz"); map.put(0,"fizz buzz"); } public List fizzBuzz(int n) { List ret = new ArrayList<>(); for(int i=1;i<=n;i++){ int key = i%15; if(map.containsKey(key)){ ret.add(map.get(key)); }else{ ret.add(""+i); } } return ret; }
2、对1进行优化,只映射3,5,8,这里需要一点数学技巧,大家看代码就理解了
public static HashMapmap = new HashMap<>(); static{ map.put(3,"fizz"); map.put(5,"buzz"); map.put(8,"fizz buzz"); } public List fizzBuzz(int n) { List ret = new ArrayList<>(); for(int i=1;i<=n;i++){ int key = f(i,3)+f(i,5); if(map.containsKey(key)){ ret.add(map.get(key)); }else{ ret.add(""+i); } } return ret; } private int f(int i,int k){ return (k-i%k)*((k-i%k)/k); }
3、利用&&的截断功能
public ListfizzBuzz(int n) { List ret = new ArrayList<>(n); for(int i=1;i<=n;i++){ String str = null; boolean bool1 = i%3==0&&(str="fizz")!=null; boolean bool2 = i%5==0&&(str="buzz")!=null&& i%3==0&&(str="fizz buzz")!=null; if(str==null){ ret.add(""+i); }else { ret.add(str); } } return ret; }
暂时想到这些,欢迎指正