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<Solution>
這題就是要把數字轉成對應的文字
可以想成將10進位,變成26進位
想法如下
- 從低位往高位做
- 取餘數,並轉換成字母
- n 除以 26,值到變成 0 為止
c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
string convertToTitle(int n) { | |
string ans; | |
while(n) { | |
ans.insert(ans.begin(), static_cast<char>(--n % 26 + 'A')); | |
n /= 26; | |
} | |
return ans; | |
} | |
}; |
kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun convertToTitle(n: Int): String { | |
val sb = StringBuilder() | |
var cnt = n | |
while(cnt > 0) { | |
val char = 'A' + (--cnt % 26) | |
sb.append(char) | |
cnt /= 26 | |
} | |
return sb.toString().reversed() | |
} | |
} |
沒有留言:
張貼留言