您好,欢迎来到尔游网。
搜索
您的当前位置:首页java —— 年号字串

java —— 年号字串

来源:尔游网

java —— 年号字串

 

【问题描述】

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

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

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

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

 

代码:提供者:@

方法一:

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

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- axer.cn 版权所有 湘ICP备2023022495号-12

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务