Ligeance

Excel中的行列数用A~Z 26个字母表示,A, B, C, D, …, Z, AA, AB, …, AZ, BA, BB, … 分别表示10进制数1, 2, 3, 4, …, 26, 27, 28, …, 52, 53, 54…。

请实现2个函数decToExcelexcelToDec,将10进制数转换为Excel数,以及将Excel数转换为10进制数。

有个小BUG,当26的时候显示为@A……不知道为啥会这样。已修复@A的BUG。

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication21
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(DecToExcel(26));
            Console.WriteLine(ExcelToDec("AB"));
        }

        static string DecToExcel(int n)
        {
            if (n <= 0)
            {
                throw new Exception("input must greater than zero");
            }
            StringBuilder sb = new StringBuilder();
            int a = 0;
            while (n > 0)
            {
                a = (n - 1) % 26;
                n = (n - 1) / 26;
                sb.Insert(0, ((char)(a + \'A\')));
            }

            return sb.ToString();
        }

        static int ExcelToDec(string input)
        {
            int result = 0;
            for (int i = 0; i < input.Length; i++)
            {
                result = result * 26 + input[i] - \'A\' + 1;
            }
            return result;
        }
    }
}
View Code

 

分类:

技术点:

相关文章:

  • 2021-04-19
  • 2022-12-23
  • 2022-01-07
  • 2021-05-29
  • 2021-05-15
  • 2021-04-16
  • 2022-02-05
  • 2022-12-23
猜你喜欢
  • 2021-12-22
  • 2021-12-01
  • 2022-03-01
  • 2021-12-08
  • 2022-01-07
  • 2022-01-03
  • 2021-10-06
相关资源
相似解决方案