Leetcode - Excel Sheet Column Number

My code:

public class Solution {
    public int titleToNumber(String s) {
        if (s == null || s.length() == 0)
            return 0;
        int number = 0;
        for (int i = 0; i < s.length(); i++)
            number = number * 26 + s.charAt(i) - 64;
        return number;
    }
}

My test result:

這道題目太簡單了,感覺有點侮辱智商。

**
總結(jié): Math
**

Anyway, Good luck, Richardo!

My code:

public class Solution {
    public int titleToNumber(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        
        int base = 1;
        int ret = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            char curr = s.charAt(i);
            int diff = (int) (curr - 'A') + 1;
            ret += diff * base;
            base *= 26;
        }
        
        return ret;
    }
}

以前的解法竟然看不懂。。。還大言不慚,侮辱智商。。。

是我變笨了嗎?

Fuck

我的思想是找規(guī)律:
A-Z: 1-26
AA-AZ: 27-52
BA-BZ: 53-78
...
AAA: 703

AAA = 1 * 26 ^ 2 + 1 * 26 ^ 1 + 1 * 26 ^ 0

從這個公式,也可以看出
Excel Sheet Column Title
那么做的原因了。

int offset = (n - 1) % 26;
while (n > 0) {
    ret = ('A' + offset) + ret;
    n = (n - 1) / 26;  // 去掉  k * (26 ^ x), here 1<=k<=26, so n - 1
    col = (n - 1) % 26; // keep finding the offset of next level
}

感覺差不多就這個思路。

Anyway, Good luck, Richardo! -- 09/05/2016

這些天有了新的思路。其實就是一個26進(jìn)制轉(zhuǎn)換。

AB

'B' * 26 ^ 0 + 'A' * 26 ^ 1
= 2 * 1 + 1 * 26 = 28

然后可以很快的寫出代碼:

My code:

public class Solution {
    public int titleToNumber(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        
        int base = 1;
        int ret = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            int offset = (int) (s.charAt(i) - 'A') + 1;
            ret += base * offset;
            base *= 26;
        }
        
        return ret;
    }
}

終于變成了 easy

Anyway, Good luck, Richardo! -- 09/19/2016

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容