- 现在有一个数字与字母的映射表,且有以下规则:
映射表:
数字 | 字母 |
3 | A |
7 | B |
9 | C |
规则:
- 碰到当前数字时,使用字母替换,例如,3-> A
- 碰到当前数字的倍数时,使用字母替换, 例如:6->A
- 碰到多个数字的倍数时,使用多个对应的字母替代,例如:21 -> AB,27->AC
请根据映射表和规则,给出0-100之间的转换结果,提示:不要直接在for循环中使用if判断,尽可能的使用设计模式。
package com.example.demo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* 演示应用程序
*
* @author 97884
* @date 2023/06/13
*/
@Slf4j
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
// 0-100
for (int i = 0; i <= 100; i++) {
String str = enumSingleton.INSTANCE.getMapping(i);
String mapping = StringUtils.hasText(str) ? str : i + "";
log.info("数字:" + i + ";映射字母:" + mapping);
}
}
}
/**
* enum单例
*
* @author 97884
* @date 2023/06/13
*/
enum enumSingleton {
INSTANCE;
/**
* 得到映射
*
* @param num 整数
* @return {@link String}
*/
public String getMapping(Integer num) {
if (num == 0) {
return null;
}
String str = null;
StringBuilder sb = new StringBuilder();
HashMap<Integer, String> map = new HashMap<>();
map.put(3,"A");
map.put(5,"B");
map.put(7,"C");
if (map.containsKey(num)) {
str = map.get(num);
} else {
for (Map.Entry<Integer, String> entry : map.entrySet()) {
Integer key = entry.getKey();
String value = entry.getValue();
str = num % key == 0 ? sb.append(value).toString() : sb.toString();
}
}
return str;
}
}