Codeforces 1B Spreadsheets

首先需要判断输入是Excel格式还是RC格式的串。判断方法:如果在读入到数字之后又读到字母,就是RC格式;否则就是Excel格式。

转换时,Excel格式的列名相当于26进制的数,但不完全一致:Z代表26而不是0。需要在转换时注意一下trick。

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

namespace _1B
{
    class Program
    {

        static int mod26(int col)
        {
            int ret = col % 26 - 1;
            if (ret == -1)
            {
                ret += 26;
            }
            return ret;
        }

        static int CalcRCColName(string Excel_C)
        {
            int C = 0;
            for (int i = 0; i < Excel_C.Length; i++)
            {
                C *= 26;
                C += Excel_C[i] - 'A' + 1;
            }
            return C;
        }

        static string CalcExcelColName(int col)
        {
            string ret = "";
            while(true)
            {
                ret = ((char)('A' + (mod26(col)))).ToString() + ret;
                int adjust = 0;
                if (col % 26 == 0)
                {
                    adjust = 1;
                }
                col = col / 26 - adjust;
                if (col == 0 )
                    break;
            }
            return ret;
        }

        static string RCToExcel(string position)
        {
            int c_pos = position.IndexOf('C');
            int R = int.Parse(position.Substring(1, c_pos - 1));
            int C = int.Parse(position.Substring(c_pos + 1));
            string Excel_C = CalcExcelColName(C);
            return Excel_C + R.ToString();
        }

        static string ExcelToRC(string position)
        {
            int num_pos = position.IndexOfAny("0123456789".ToArray());
            string C = position.Substring(0, num_pos);
            string R = position.Substring(num_pos);
            int RC_C = CalcRCColName(C);

            return "R" + R + "C" + RC_C.ToString();
        }

        static bool IsExcelFormat(string position)
        {
            int state = 0;
            foreach(var c in position)
            {
                if (char.IsDigit(c))
                {
                    if (state == 0)
                        state = 1;
                }
                else
                {
                    if (state == 1)
                        return false;
                }
            }
            return true;
        }

        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            while(n-- != 0)
            {
                string pos = Console.ReadLine();
                if (IsExcelFormat(pos))
                {
                    Console.WriteLine(ExcelToRC(pos));
                }
                else
                {
                    Console.WriteLine(RCToExcel(pos));
                }
            }
        }
    }
}

Default Comments (0)

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Disqus Comments (0)

dontpanic92-cn