知之者 不如好之者, 好之者 不如樂之者

기계처럼 살지 말고, 즐기는 인간이 되자

Code/LeetCode

[LeetCode] 168. Excel Sheet Column Title (Easy/Python)

코방코 2022. 9. 29. 13:45
728x90
 

Excel Sheet Column Title - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Above is the link to the problem.

 

Problem

Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

For example:

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

Example 

Input: columnNumber = 701
Output: "ZY"

 

Analysis

1 to 26 are considered A to Z.

And columnNumber = 27 must print 'AA'

if we divide 27 by 26 and get the quotient and remainder, both are 1

Because of this, we print 27 to 'AA'

 

But there is one problem.

if we divide 26 by 26, then we get the quotient = 1 and remainder = 0.

then the program can't compute 0 here.

So error must occur.

 

We can solve this problem like this.

If the remainder gets 0, then the remainder be 26 and the quotient subtracts 1  

 

For example, if columnNumber is 26, the original result is quotient = 1 and remainder = 0,

but in this excel column, we think of this as quotient = 0 and remainder = 26

 

This is more example when columnNumber = 701

 

I solved this problem by the below code.

 

ASCII code : A=65 ~ Z=90 in the decimal number.

 

This code gets the top 0.78% of time efficiency and uses 13.9 MB of memory.

 

 

728x90
반응형