作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


[LeetCode]

题目地址:https://leetcode.com/problems/excel-sheet-column-number/

Total Accepted: 77115 Total Submissions: 185238 Difficulty: Easy

题目大意

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

解题方法

典型的26进制题目啊!没啥难度。

重点是26进制中每一位对应的26的多少次幂。不要搞错。另外,为了防止计算时间过
长,而且避免数据转化,没有采用Math.exp的方法。直接手撸26的次幂。

Java解法

算法如下:

public class Solution {
public int titleToNumber(String s) {
int answer=0;
char[] nums=s.toCharArray();
for(int i=0; i<nums.length; i++){
int temp=nums[i]-'A'+1;//字幕代表的数字是多少
for(int j=0; j<nums.length-i-1; j++){//注意循环的次数
temp*=26;
}
answer+=temp;
}
return answer;
}
}

AC:2ms

Python解法

python的代码总是那么短。

class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
res = 0
for c in s:
res = 26 * res + ord(c) - ord("A") + 1
return res

日期

2016/4/30 14:42:55
2018 年 11 月 11 日 —— 剁手节快乐

最新文章

  1. 中国版的 Office 365
  2. SQL Server 子查询
  3. Razor视图引擎输出没有编码的 Html 字符串
  4. codevs2606 约数和问题
  5. PQ格式化虚拟机硬盘如何生效
  6. ubuntu12.04 修复Grub2
  7. AcceptEx编辑
  8. 初识XML及简单工厂运用--网络电视精灵
  9. postgresql行转列并拼接字符串
  10. Java中的成员初始化顺序和内存分配过程
  11. [转载]通过jQuery的attr修改onclick
  12. springmvc+mybatis+mysql 数据库插入中文是乱码
  13. [LeetCode] Reorganize String 重构字符串
  14. JavaScript是如何工作的:事件循环和异步编程的崛起 + 5种使用 async/await 更好地编码方式!
  15. HZNU ACM一日游 2019.3.17 【2,4,6-三硝基甲苯(TNT)】
  16. for循环中break与continue的区别
  17. Python 隔离沙箱 virtualenv
  18. POJ 1063 - Flip and Shift
  19. C# if else 使物体在X轴循环移动
  20. .netcore使用vscode多项目调试

热门文章

  1. Bedtools如何比较两个参考基因组注释版本的基因?
  2. Python通过subprocess.Popen.poll控制流程
  3. Oracle-创建新表,创建备份表,对表中插入多条数据
  4. javaSE基础知识(走向编程的门口)— 更新完毕
  5. 日常Java 2021/11/16
  6. 学习java 7.1
  7. Angular中@Output()的使用方法
  8. Set &amp;&amp; Map
  9. maven根据profile,resources,filters来区分部署环境
  10. 前端两大框架 vue 和 react 的区别