java —— 年号字串

java —— 年号字串

 

【问题描述】

小明用字母 A 对应数字 1,B 对应 2,以此类推,用 Z 对应 26。

对于 27 以上的数字,小明用两位或更长位的字符串来对应,

例如 AA 对应 27,AB 对 应 28,AZ 对应 52,LQ 对应 329。

请问 2019 对应的字符串是什么?

 

代码:提供者:@Jplusztx

方法一:

public class Main {
    public static void main(String[] args) {
       Scanner stdIn = new Scanner(System.in);
       int num = stdIn.nextInt();
       String ans = "";
       while (num != 0) {
           int temp = num % 26;
           num /= 26;
           if (temp == 0) {
               ans = "Z" + ans;
               num --;
           } else {
               ans = (char)('A' + temp - 1) + ans;
           }
       }
       System.out.println(ans);
    }
}

方法二:使用递归

public class Main {
    public static void main(String[] args) {
       Scanner stdIn = new Scanner(System.in);
       int num = stdIn.nextInt();
       System.out.println(change(num));
    }

    public static String change (int num) {
        if (num == 0) return "";
        int temp = num % 26;
        int nextN = n / 26;
        if (temp == 0 ) {
            return exchange(nextN - 1) + 'Z';
        }
        else {
            return exchange(nextN) + (char)('A' + temp - 1);
        }
    }
}

思路:

当输入的数为26的倍数时则最后一位一定是‘Z’(78:BZ、52:AZ)
当输入的数为26的倍数+(n)时(n小于26),最后一位都会向前进n-1(即从‘A’+n-1),
同时倒数第二个字母会向前进 1;
(若前面没有字母就从就进‘A’,若有字母如 52:AZ,53为26*2 + 1,因此‘A’就进1变为‘B’,Z就重头开始从‘A’+1-1=‘A',所以53:’BA‘)
此时的n的相当于输入的数mod26的余数;

 

 

#END

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值