给你一个整数n. 从 1 到 n 按照下面的规则打印每个数:
fizz
.buzz
.3
和5
整除,打印fizz buzz
.3
整除也不能被 5
整除,打印数字本身。
只用一个if判断
比如 n = 15
, 返回一个字符串数组:
[
"1", "2", "fizz",
"4", "buzz", "fizz",
"7", "8", "fizz",
"buzz", "11", "fizz",
"13", "14", "fizz buzz"
]
package com.leolee.dataStructure;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/**
* @ClassName Test
* @Description:
* @Author LeoLee
* @Date 2020/10/28
* @Version V1.0
**/
public class Test {
/*
* 功能描述: <br>
* 〈正常思路的算法〉
* @Param: [n]
* @Return: void
* @Author: LeoLee
* @Date: 2020/11/1 15:55
*/
public static void normal(int n) {
List<String> result = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i%3 == 0 && i%5 != 0) {
result.add("fizz");
} else if (i%3 != 0 && i%5 == 0) {
result.add("buzz");
} else if (i%3 == 0 && i%5 == 0) {
result.add("fizz buzz");
} else {
result.add(String.valueOf(i));
}
}
result.forEach(e -> {
System.out.print(e + ",");
});
System.out.println();
}
//---------------------------------------------------------------------
//只使用一个if判断解题
//---------------------------------------------------------------------
public static void onlyOneIf(int n) {
List<String> result = new ArrayList<>();
Map<Integer, String> m3 = new HashMap();
m3.put(3, "fizz ");
Map<Integer, String> m5 = new HashMap();
m5.put(5, " buzz");
for (int i = 1; i <= n; i++) {
String str1 = m3.get(i%3+3);
String str2 = m5.get(i%5+5);
str2 = str1 + str2;
str2 = str2.replaceFirst(" ", "");
str2 = str2.replaceAll("null", "");
if (str2.length() == 0) {
str2 = String.valueOf(i);
}
result.add(str2);
}
result.forEach(e -> {
System.out.print(e + ",");
});
System.out.println();
}
public static void onlyOneIf2(int n) {
List<String> result = new ArrayList<>();
Function function = num -> {
int m = Integer.valueOf(String.valueOf(num));
return (Object) (m%3 == 0 ? (m%5 == 0 ? "fizz buzz" : "fizz") : (m%5 == 0 ? "buzz" : m + ""));
};
for (int i = 1; i <= n; i++) {
result.add(String.valueOf(function.apply(i)));
}
result.forEach(e -> {
System.out.print(e + ",");
});
System.out.println();
}
public static void main(String[] args) {
Test.normal(20);
Test.onlyOneIf(20);
Test.onlyOneIf2(20);
}
}
通常的解题方法就是使用三元运算的嵌套:
m%3 == 0 ? (m%5 == 0 ? "fizz buzz" : "fizz") : (m%5 == 0 ? "buzz" : m + "")