• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Excel Sheet Column Number

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 

就是把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开始

26进制

复杂度

时间 O(N) 空间 O(1)

思路

得到数字,其实就是把26进制的数转换为10进制的数。算法就是基本的进制转换方法,从后往前第n位的值乘上26^(n-1)。这里26进制数是1开始的,即A是1。

 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 }

 

posted @ 2015-01-07 11:39  neverlandly  阅读(327)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3