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

171. Excel Sheet Column Number

2019-11-08 02:37:49
字体:
来源:转载
供稿:网友

题目

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 -> 1B -> 2C -> 3...Z -> 26AA -> 27AB -> 28

Credits: Special thanks to @ts for adding this PRoblem and creating all test cases.

Subscribe to see which companies asked this question.


思路

26进制转10进制,按数学方法来就行,注意溢出等场景


代码

class Solution {public: int titleToNumber(string s) { //26进制转10进制 size_t length = s.size(); if(length == 0) { return 0; } long times = 1; long sum = 0; int tempNum = 0; for(int i = length - 1;i >= 0 ;i--) { //最后一位转换10进制 tempNum = s[i] - 'A' + 1; sum += tempNum * times; if(sum > INT_MAX) { return INT_MAX; } //系数累乘 times *= 26; } return (int)sum; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表