• Leetcode 168. Excel Sheet Column Title


    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 

    思路:
    1 = 1 * 26 ^ 0 -> A
    ...
    26 = 26 * 26 ^ 0 -> Z
    27 = 1 * 26 ^ 1 + 1 * 26 ^ 0 -> AA
    28 = 1 * 26 ^ 1 + 2 * 26 ^ 0 -> AB
    ...
    可以发现1对应'A' , 2对应'B',比如我们怎么得到AB呢?首先我们对n % 26,那么由数论知识,已知就得到2了,这个2就可以得到'B',接下来n = n / 26, 即 28 / 26 = 1 * 26 ^ 0 + 0,直到n <= 0.显然我们很容易得到了这个1,也就得到了'A',将连接起来的字符串反转,也就是"AB"了。
    注意:26怎么处理呢?以及52又怎么办呢?那么这里我们只需要另外加个条件就行了:if(n % 26 == 0) 0对应的是'Z'.并且要n = n - 26,再进行后面 n = n / 26的处理。
    比如 52 = 1 * 26 ^1 + 26 * 26 ^ 0,52对应的是AZ。首先52 % 26 = (1 * 26 ^ 1 + 26 * 26 ^ 0) % 26 = 0,所以我们输出一个'Z',如果不进行n = n - 26,去除掉最低位的个位数,那么 52 / 26 = (1 * 26 ^ 0 + 1 * 26 ^ 0) = 2 * 26 ^ 0,那么得到的就是2即'B'了,出错。

     1 class Solution {
     2 public:
     3     string convertToTitle(int n) {
     4         string s = "";
     5         char c;
     6         while(n >= 1){
     7             if(n % 26 == 0){
     8                 n -= 26;
     9                 c = 'Z';
    10             }
    11             else 
    12                 c = 'A' + (n % 26 - 1);
    13             s += c;
    14             n = n / 26;
    15         }
    16         reverse(s.begin(), s.end());
    17         return s;
    18     }
    19 };
    
    

    也可以用递归的:

     1 #include <iostream>
     2 using namespace std;
     3 void convertToTitle(int n){
     4     if(n <= 0)
     5         return;
     6     if(n % 26 == 0)
     7         n = n - 26;
     8     convertToTitle(n / 26);
     9     if(n % 26 == 0){
    10         cout << 'Z';
    11     } else {
    12         cout << (char)('A' + (n % 26) - 1);
    13     }
    14 }
    15 
    16 int main(){
    17     int n;
    18     while(cin >> n){
    19         convertToTitle(n);
    20         cout << endl;
    21     }
    22     return 0;
    23 }
    
    


  • 相关阅读:
    hibernate 使用hibernate 的注解做多对一双向映射
    JBPM学习笔记
    在测试Hibernate的一对多双向关联映射时
    js定时三秒后自动跳转页面
    struts2 的验证框架
    hibernate 双向一多对关联 删除一端时级联删除多端
    JPA 一些常用的东西
    Python 基础语法
    设计一个带有getmin功能的栈,保证时间复杂度在O(1)
    数据结构栈模拟队列
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/5848788.html
Copyright © 2020-2023  润新知