C++实现LeetCode(168.求Excel表列名称)

[LeetCode] 168.Excel Sheet Column Title 求Excel表列名称

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

    1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...

Example 1:

Input: 1
Output: "A"

Example 2:

Input: 28
Output: "AB"

Example 3:

Input: 701
Output: "ZY"

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases.

此题和 Excel Sheet Column Number 是一起的,但是我在这题上花的时间远比上面一道多,其实原理都一样,就是一位一位的求,此题从低位往高位求,每进一位,则把原数缩小26倍,再对26取余,之后减去余数,再缩小26倍,以此类推,可以求出各个位置上的字母。最后只需将整个字符串翻转一下即可。我们先从最简单的来看,对于小于26的数字,那么我们只需要对26取余,然后减去1,加上字符A即可,但是对于26来说,如果还是这么做的话就会出现问题,因为对26取余是0,减去1后成为-1,加上字符A后,并不等于字符Z。所以对于能被26整除的数我们得分开处理,所以就分情况讨论一下吧,能整除26的,直接在结果res上加上字符Z,然后n自减去26;不能的话,就按照一般的处理,n要减去这个余数。之后n要自除以26,继续计算下去,代码如下:

解法一:

class Solution {
public:
    string convertToTitle(int n) {
        string res = "";
        while (n) {
            if (n % 26 == 0) {
                res += 'Z';
                n -= 26;
            } else {
                res += n % 26 - 1 + 'A';
                n -= n % 26;
            }
            n /= 26;
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

然后我们可以对上面对方法进行下优化,合并if和else,写的更简洁一些。从上面的讲解中我们得知,会造成这种不便的原因是能被26整除的数字,无法得到字符Z。那么我们用一个小trick,比如对于26来说,我们先让n自减1,变成25,然后再对26取余,得到25,此时再加上字符A,就可以得到字符Z了。叼就叼在这对其他的不能整除26的数也是成立的,完美解决问题,参见代码如下:

解法二:

class Solution {
public:
    string convertToTitle(int n) {
        string res;
        while (n) {
            res += --n % 26 + 'A';
            n /= 26;
        }
        return string(res.rbegin(), res.rend());
    }
};

这道题还可以用递归来解,而且可以丧心病狂的压缩到一行代码来解:

解法三:

class Solution {
public:
    string convertToTitle(int n) {
        return n == 0 ? "" : convertToTitle(n / 26) + (char)(--n % 26 + 'A');
    }
};

类似题目:

Excel Sheet Column Number

参考资料:

https://leetcode.com/problems/excel-sheet-column-title/

https://leetcode.com/problems/excel-sheet-column-title/discuss/51399/Accepted-Java-solution

https://leetcode.com/problems/excel-sheet-column-title/discuss/51398/My-1-lines-code-in-Java-C%2B%2B-and-Python

https://leetcode.com/problems/excel-sheet-column-title/discuss/51421/Share-my-simple-solution-just-a-little-trick-to-handle-corner-case-26

到此这篇关于C++实现LeetCode(168.求Excel表列名称)的文章就介绍到这了,更多相关C++实现求Excel表列名称内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++实现LeetCode(166.分数转循环小数)

    [LeetCode] 166.Fraction to Recurring Decimal 分数转循环小数 Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. Fo

  • C++实现LeetCode165.版本比较)

    [LeetCode] 165.Compare Version Numbers 版本比较 Compare two version numbers version1 and version2. If version1 > version2 return 1; if version1 <version2 return -1;otherwise return 0. You may assume that the version strings are non-empty and contain onl

  • C++实现LeetCode(164.求最大间距)

    [LeetCode] 164. Maximum Gap 求最大间距 Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Return 0 if the array contains less than 2 elements. Example 1: Input: [3,6,9,1] Output: 3 Explanation: The sor

  • C++实现LeetCode(171.求Excel表列序号)

    [LeetCode] 171.Excel Sheet Column Number 求Excel表列序号 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 -&g

  • C++实现LeetCode(162.求数组的局部峰值)

    [LeetCode] 162.Find Peak Element 求数组的局部峰值 A peak element is an element that is greater than its neighbors. Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. The array may contain multiple peaks, in that c

  • C++实现LeetCode(228.总结区间)

    [LeetCode] 228.Summary Ranges 总结区间 Given a sorted integer array without duplicates, return the summary of its ranges. Example 1: Input:  [0,1,2,4,5,7] Output: ["0->2","4->5","7"] Explanation: 0,1,2 form a continuous ran

  • C++实现LeetCode(167.两数之和之二 - 输入数组有序)

    [LeetCode] 167.Two Sum II - Input array is sorted 两数之和之二 - 输入数组有序 Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of t

  • C++实现LeetCode(163.缺失区间)

    [LeetCode] 163. Missing Ranges 缺失区间 Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, upper], return its missing ranges. Example: Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99, Output: ["2&q

  • C++实现LeetCode(168.求Excel表列名称)

    [LeetCode] 168.Excel Sheet Column Title 求Excel表列名称 Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example:     1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ... Example 1: Input: 1 O

  • Go Java算法之Excel表列名称示例详解

    目录 Excel表列名称 方法一:数学(Java) 方法一:数学(Go) Excel表列名称 给你一个整数 columnNumber ,返回它在 Excel 表中相对应的列名称. 例如: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... 示例 1: 输入:columnNumber = 1 输出:"A" 示例 2: 输入:columnNumber = 28 输出:"AB"

  • C#实现Excel表数据导入Sql Server数据库中的方法

    本文实例讲述了C#实现Excel表数据导入Sql Server数据库中的方法.分享给大家供大家参考,具体如下: Excel表数据导入Sql Server数据库的方法很多,这里只是介绍了其中一种: 1.首先,我们要先在test数据库中新建一个my_test表,该表具有三个字段tid int类型, tname nvarchar类型, tt nvarchar类型 (注意:my_test表中的数据类型必须与Excel中相应字段的类型一致) 2. 我们用SELECT * FROM  OPENROWSET(

  • C#语言MVC框架Aspose.Cells控件导出Excel表数据

    本文实例为大家分享了Aspose.Cells控件导出Excel表数据的具体代码,供大家参考,具体内容如下 控件bin文件下载地址 @{ ViewBag.Title = "xx"; } <script type="text/javascript" language="javascript"> function getparam() { var param = {}; param.sear = $("#sear").t

  • Java中excel表数据的批量导入方法

    本文实例为大家分享了Java中excel表数据的批量导入,供大家参考,具体内容如下 首先看下工具类: import java.awt.Color; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.lang.ref

  • C++实现LeetCode(128.求最长连续序列)

    [LeetCode] 128.Longest Consecutive Sequence 求最长连续序列 Given an unsorted array of integers, find the length of the longest consecutive elements sequence. Your algorithm should run in O(n) complexity. Example: Input: [100, 4, 200, 1, 3, 2] Output: 4 Expl

  • C++实现LeetCode(169.求大多数)

    [LeetCode] 169. Majority Element 求大多数 Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. Example 1

  • SQL实现LeetCode(175.联合两表)

    [LeetCode] 175.Combine Two Tables 联合两表 Table: Person +-------------+---------+ | Column Name | Type    | +-------------+---------+ | PersonId    | int     | | FirstName   | varchar | | LastName    | varchar | +-------------+---------+ PersonId is the

  • asp读取excel表名的实现代码

    看代码: 复制代码 代码如下: <%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%> <% dim conn,rs,excelFileName excelFileName=Server.MapPath("Data/test.xls") set conn = Server.CreateObject("ADODB.Connection") conn.connectionstring=

随机推荐