算法题:数字与字母映射

  1. 现在有一个数字与字母的映射表,且有以下规则:

映射表:

数字

字母

3

A

7

B

9

C

规则:

  1. 碰到当前数字时,使用字母替换,例如,3-> A
  2. 碰到当前数字的倍数时,使用字母替换, 例如:6->A
  3. 碰到多个数字的倍数时,使用多个对应的字母替代,例如: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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值