zoukankan      html  css  js  c++  java
  • 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--26 (A--Z)

    26+1--26+26 (AA--AZ)

    26+26+1--26+26+26 (BA--BZ)

    设给定的数字为n,我们要想办法先把最后的余位给求出来,因为余位是1--26 (A--Z),

    而求余运算的结果是会出现0的,所以我们通过 (n - 1) % 26来算,这样就变成了0--25 对应 (A--Z)。

    求完余后,继续求前一位,通过(n - 1) / 26把余位给消除。

     1 class Solution {
     2 public:
     3     string convertToTitle(int n) {
     4         string res;
     5         while (n)
     6         {
     7             res = (char)((n - 1) % 26 + 'A') + res;
     8             n = (n - 1) / 26;
     9         }
    10         return res;
    11     }
    12 };
  • 相关阅读:
    每日总结
    每日总结
    每日总结
    每日总结
    每日总结
    每日总结
    每日总结
    每日总结
    团队博客
    团队博客
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4910170.html
Copyright © 2011-2022 走看看