chengchengxu15 / CS-leaning

1 stars 1 forks source link

Excel Sheet Column Title #2

Closed chengchengxu15 closed 3 years ago

chengchengxu15 commented 3 years ago

lentcode: https://www.lintcode.com/problem/1350/?_from=collection&fromId=29 leetcode: https://leetcode.com/problems/excel-sheet-column-title/

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

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

first time 07/12/2021

chengchengxu15 commented 3 years ago

Note:

It takes time for me to debug: +1 -1 ...

chengchengxu15 commented 3 years ago

My solution (it works, but stupid...)

class Solution:
    """
    @param n: a integer
    @return: return a string
    """
    def convertToTitle(self, n):
        # write your code here
        dict = {1:"A",
                2:"B",
                3:"C",
                4:"D",
                5:"E",
                6:"F",
                7:"G",
                8:"H",
                9:"I",
                10:"J",
                11:"K",
                12:"L",
                13:"M",
                14:"N",
                15:"O",
                16:"P",
                17:"Q",
                18:"R",
                19:"S",
                20:"T",
                21:"U",
                22:"V",
                23:"W",
                24:"X",
                25:"Y",
                0:"Z",
                26:"Z"
                }
        if n <= 0:
            return ""
        else:
            result = ""
            q = 1
            while q > 0:
                q = (n-1)//26
                m = (n-1)%26
                n = q
                result = dict[(m+1)] + result
            return result
chengchengxu15 commented 3 years ago

Solution 2, better:

class Solution:
    """
    @param n: a integer
    @return: return a string
    """
    def convertToTitle(self, n):
        # write your code here
        string = "ZABCDEFGHIJKLMNOPQRSTUVWXYZ"
        if n <= 0:
            return ""
        else:
            result = ""
            q = 1
            while q > 0:
                q = (n-1)//26
                m = (n-1)%26
                n = q
                result = string[m+1] + result
            return result
chengchengxu15 commented 3 years ago

Solution:

class Solution:
    """
    @param n: a integer
    @return: return a string
    """
    def convertToTitle(self, n):
        # write your code here
        result = [] 
        while n > 0: 
          c = chr((n - 1) % 26 + ord('A')) 
          result.append(c) 
          n = (n - 1) // 26 
        return ''.join(result[::-1])