zoukankan      html  css  js  c++  java
  • [LeetCode]:171: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进制,从低到高按位计算

    代码:

    public class Solution {
        public static int titleToNumber(String s) {
            int intResult = 0;
            char[]chars=s.toCharArray();
            int n =0;
            for(int i = chars.length; i>0;i--){
                intResult = intResult + ((int)chars[i-1]-64)*caleOffset(n);
                n++;
            }
            return intResult;
        }
       
        public static int caleOffset(int n) {
            int intResult = 1;
            for(int i = 0; i< n;i++){
                intResult = intResult*26;
            }
            return intResult;
        }
    }

    高手的代码:从高位到低位,进位乘以26

    class Solution {
    public:
        int titleToNumber(string s) {
            int ret = 0;
            for(int i = 0; i < s.size(); i ++)
                ret = ret*26 + (s[i]-'A'+1);
            return ret;
        }
    };
  • 相关阅读:
    20210131
    20210130
    20210129
    20210128
    20210127
    例3-7
    例3-5
    例3-4
    例3-3
    例3-2
  • 原文地址:https://www.cnblogs.com/savageclc26/p/4808240.html
Copyright © 2011-2022 走看看