LeetCode-171 Excel Sheet Column Number

本文介绍了一种将Excel列标题转换为对应数字的方法,并提供了三种实现方式:使用map进行映射、直接转换以及避免使用pow()函数。每种方法都附带了具体的C++代码实现及耗时对比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://leetcode.com/problems/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 

1、首先建立A-Z 与1-26的map,扫描字符串时调用,转换即采用26进制的计算,耗时(20ms)

class Solution {

public:
    int titleToNumber(string s) {
        map<char,int> m;
        for(char c = 'A';c<='Z';c++){
            m.insert(pair<char,int> (c,c-'A'+1));
        }
        int len = s.length(),sum = 0;
        for(int i = 0;i<len;i++){
            sum += m[s[i]]*pow(26,len-1-i);
        }
        return sum;
    }

};

2、直接扫描字符串转换,耗时(8ms)

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

2、不采用pow(),耗时(12ms)

class Solution {
public:
    int titleToNumber(string s) {
        int len = s.length(),sum = 0,temp,i;
        for(i = 0;i<len-1;i++){
            temp = s[i] - 'A' + 1;
            sum = (sum+temp)*26;
        }
        return sum + s[i] - 'A' + 1;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值