五笔的编码与解码

面试题:五笔的编码范围是a到y的25个字母,从1位到4位的编码,

如果将五笔的编码按字典序排序,形成数组如下:a, aa, aaa, aaaa, aaab, aaac, …, b, ba, baa, baaa, baab…yyyx, yyyy

其中a的索引是0,aa的索引是1,aaa的索引是2,aaaa的索引是3,以此类推:

1)、编写一个函数,输入是任意一个合法的字符串,输出这个字符串对应的索引;

2)、编写一个函数,输入是任意一个合法的索引,输出这个索引对应的字符串。
代码实现:

using System;

namespace cchoop
{
    class Program
    {

        public static void Main()
        {
            Console.WriteLine(GetWubiIndexByStr("a"));
            Console.WriteLine(GetWubiIndexByStr("aa"));
            Console.WriteLine(GetWubiIndexByStr("aaa"));
            Console.WriteLine(GetWubiIndexByStr("aaaa"));
            Console.WriteLine(GetWubiIndexByStr("aaab"));
            Console.WriteLine(GetWubiIndexByStr("b"));

            Console.WriteLine(GetWubiStrByIndex(0));
            Console.WriteLine(GetWubiStrByIndex(1));
            Console.WriteLine(GetWubiStrByIndex(2));
            Console.WriteLine(GetWubiStrByIndex(3));
            Console.WriteLine(GetWubiStrByIndex(4));
            Console.WriteLine(GetWubiStrByIndex(9));
        }

        public static int GetWubiIndexByStr(string wubiStr)
        {
            //权重
            int[] factor = new int[] { 1 + 25 + 25 * 25 + 25 * 25 * 25, 1 + 25 + 25 * 25, 1 + 25, 1 };
            int index = wubiStr.Length - 1;
            for (int i = 0; i < wubiStr.Length; i++)
            {
                index += factor[i] * (wubiStr[i] - 'a');
            }
            return index;
        }
        public static string GetWubiStrByIndex(int index)
        {
            //权重
            int[] factor = new int[] { 1 + 25 + 25 * 25 + 25 * 25 * 25, 1 + 25 + 25 * 25, 1 + 25, 1 };
            char[] arr = new char[4];

            int i = 0;
            while (index > 0)
            {
                arr[i] = (char)('a' + index / factor[i]);
                index = index % factor[i];
                index--;
                i++;
            }

            return new string(arr).TrimEnd();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cchoop

有用的话请杯肥宅水

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值