baidu笔试的2个题目题目一解析

来源:互联网 发布:win7电脑桌面主题软件 编辑:程序博客网 时间:2024/06/06 17:27

序列Seq=[a,b,…z,aa,ab…az,ba,bb,…bz,…,za,zb,…zz,aaa,…] 类似与excel的排列,任意给出一个字符串s=[a-z]+(由a-z字符组成的任意长度字符串),请问s是序列Seq的第几个。
程序解析:
public class Test1 {   

public static void main(String[] args) {       

      int n = letter2Number("abc");       

      System.out.println(n);   

 }   

public static int letter2Number(String letters) {       

if(!letters.matches("[a-zA-Z]+")) {

            throw new IllegalArgumentException("Format ERROR!");        }//这位兄弟考虑到了输入非字母的情况 

       char[] chs = letters.toLowerCase().toCharArray(); //这句话很简单把字符串打散成字符数组

        int result = 0;

        for(int i = chs.length - 1, p = 1; i >= 0; i--) { 

            result += getNum(chs[i]) * p;

            p *= 26; 

       }

        return result; 

   }   

 private static int getNum(char c) { 

       return c - 'a' + 1;//这句话貌似是把字母转换成对应的十进制数1-26  

  }

}

原创粉丝点击