一个有趣的进制转换题

我们在用Excel时,会遇到列的编号是这样的 A,B...Z, AA,AB...ZZ,AAA,AAB...ZZZ,AAAA...现在我们需要编写一个程序来完成如下的工作,当我们输入一个数字来表示第几行(以0开始)时,方法返回正确的Excel中对应的字符串标号。比如0返回A,25返回Z,26返回AA。

也许起初你认为这不就是把一个十进制的数转换成二十六进制的数然后用A-Z表示0-25之间的数就ok了,那样的话,你就小瞧这道题了,你会发现你的程序输出Z后会输出BA,但我们期望的却是AA,问题出在哪了里?其实问题很简单,这个序列它其实不完全是26进制,当数的位数多于1位时,它变成了27进制,此时A-Z不再表示0-25,而是1-26。下面是我的程序:

        public static string Convert26(long input)
        {
            if (input == 0)
            {
                return "A";
            }

            List<char> result = new List<char>();
            //on-off flag,used to indicate whether current number we will capture is not the fist one.
            bool isFirst = true;
            //the number is the system.
            int baseNumber = 26;

            while (input != 0)
            {
                char current;
                if (isFirst)
                {
                    isFirst = false;
                    current = Convert.ToChar(input % baseNumber + 'A');
                }
                else
                {

                    //the system become 27
                    baseNumber = 27;
                    current = Convert.ToChar((input-1) % 26 + 'A');
                }
                result.Add(current);
                input = input / baseNumber;
            }
            result.Reverse();
            return new string(result.ToArray());
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值