flowingfog

偶尔刷题

  博客园  :: 首页  :: 新随笔  :: 联系 ::  :: 管理

分析

难度 易

来源

https://leetcode.com/problems/excel-sheet-column-number

题目

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 
    ...

Example 1:

Input: "A"
Output: 1

Example 2:

Input: "AB"
Output: 28

Example 3:

Input: "ZY"
Output: 701

解答

Runtime: 1 ms, faster than 100.00% of Java online submissions for Excel Sheet Column Number.

 1 package LeetCode;
 2 
 3 public class L171_ExcelSheetColumnNumber {
 4     public int titleToNumber(String s) {
 5         int len=s.length();
 6         int colNum=0;
 7         int base=1;//当前位的1表示的大小
 8         for(int i=len-1;i>=0;i--){
 9             colNum+=(int)(s.charAt(i)-64)*base;
10             base*=26;
11         }
12         return colNum;
13     }
14     public static void main(String[] args){
15         L171_ExcelSheetColumnNumber l171=new L171_ExcelSheetColumnNumber();
16         String s="AB";
17         System.out.println(l171.titleToNumber(s));
18     }
19 }

 

 

posted on 2018-11-14 10:37  flowingfog  阅读(175)  评论(0编辑  收藏  举报