Discover more from DMITRII’s Substack
I post a problem that I solve every single day
Continue reading
# 22.08.2023 [168. Excel Sheet Column Title]
Excel col number to letter-number `1` -> `A`, `28` -> `AB`
22.08.2023
168. Excel Sheet Column Title easy
blog post
Join me on Telegram
https://t.me/leetcode_daily_unstoppable/316
Problem TLDR
Excel col number to letter-number 1
-> A
, 28
-> AB
Intuition
Just arithmetic conversion of number to string with radix of 26
instead of 10
. Remainder from division by 26 gives the last letter. Then the number must be divided by 26.
Approach
use a StringBuilder
number must be
n-1
Complexity
Time complexity:
O(log(n)), logarithm by radix of 26Space complexity:
O(log(n))
Code
fun convertToTitle(columnNumber: Int): String = buildString {
var n = columnNumber
while (n > 0) {
insert(0, ((n - 1) % 26 + 'A'.toInt()).toChar())
n = (n - 1) / 26
}
}