zoukankan      html  css  js  c++  java
  • 171. 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 
    本质:26进制转换为10进制
    以下这个例子是错误的,因为比如AB,按字符串的顺序排在第一位的是A而不是B

    class Solution {
    public:
    int titleToNumber(string s) {
    int ret = 0;
    for(int i = 0; i < s.size(); i ++)
    {
    int m=pow(26,i);
    ret +=(s[i]-'A'+1)*m;
    }
    return ret;
    }
    };

    正确的是:

    class Solution {
    public:
    int titleToNumber(string s) {
    int ret = 0;
    int n=s.size();
    for(int i = 0; i < n; i ++)
    {
    int m=pow(26,n-1-i);
    ret +=(s[i]-'A'+1)*m;
    }
    return ret;
    }
    };

    这样也是对的

    1. class Solution {  
    2. public:  
    3.     int titleToNumber(string s) {  
    4.         int sum = 0;  
    5.         int tmp = 0;  
    6.         for (int i = 0; i < s.length(); ++i) {  
    7.             tmp = s[i] - 'A' + 1;  
    8.             sum = 26 * sum + tmp;  
    9.         }  
    10.         return sum;  
    11.     }  
    12. }; 
  • 相关阅读:
    构建账户系统
    我的vim配置
    document.readyState和xmlhttp.onreadystatechange
    RSA非对称算法实现HTTP密码加密传输
    css3动画学习资料整理
    H5缓存机制学习记录
    [leetcode]3Sum Closest
    [leetcode]Word Ladder II
    [leetcode]Two Sum
    [leetcode]Regular Expression Matching
  • 原文地址:https://www.cnblogs.com/baiyuhong/p/5101442.html
Copyright © 2011-2022 走看看