LeetCode------Excel Sheet Column Number

来源:互联网 发布:excel无法黏贴数据 编辑:程序博客网 时间:2024/06/15 06:36

题目介绍


Related to question Excel Sheet Column Title

Given a column title as appear in an Excel sheet, return its corresponding column number.

For example:

    A -> 1    B -> 2    C -> 3    ...    Z -> 26    AA -> 27    AB -> 28 


自己的解法


public class Solution {    public int titleToNumber(String s) {          int num=0;          int max=1;          int length=s.length();          char [] c =s.toCharArray();          int [] a =new int[length];          while(length!=1){              max*=26;              length--;          }          for(int i=0;i<s.length();i++){               a[i]=(int)c[i]-64;               num+=a[i]*max;               max/=26;          }          return num;    }}


题目的意思是其实就是将26进制转为10进制,每一位有对应的权值从低到高分别是26^0,26^1,26^2等等,再乘以对应为的值加起来就可以。比如说BA=2*26+1*1=53。英文数字对应的值就是相应英文字母的ASCII值减去A的ASCII值再加一。


Hot解法


public class Solution {    public int titleToNumber(String s) {        int result  = 0;        for (int i = 0; i < s.length(); i++){            result *= 26;            result += ((s.charAt(i) - 'A') + 1);            }        return result;    }}


Hot解法的思路和我们解法的思路是一样的,Hot解法将权值的计算和累加放到一起,在一个循环内就可以处理完毕,以后类似的进制转换问题,都可以采用Hot解法的写法,比较简洁,值得我们学习。





0 0
原创粉丝点击