首页 > 学院 > 开发设计 > 正文

Leetcode: Excel Sheet Column Number

2019-11-14 22:31:21
字体:
来源:转载
供稿:网友
Leetcode: Excel Sheet Column Number
Related to question Excel Sheet Column TitleGiven 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 

就是把26进制转换为10进制

 1 public class Solution { 2     public int titleToNumber(String s) { 3         int res = 0; 4         for (int i=0; i<s.length(); i++) { 5             char c = s.charAt(i); 6             res += (int)(c - 'A' + 1) * Math.pow(26, s.length()-i-1); 7         } 8         return res; 9     }10 }

从least significant bit开始

 1 public class Solution { 2     public int titleToNumber(String s) { 3         int res = 0; 4         int len = s.length(); 5         int k = 1; 6         for (int i=len-1; i>=0; i--) { 7             char c = s.charAt(i); 8             res += (int)(c-'A'+1)*k; 9             k *= 26;10         }11         return res;12     }13 }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表