Share my concise Java solution, (I also have a question in my post)


  • 0
    public int titleToNumber(String s) {
        int N = s.length()-1, res = 0;
        for (char c : s.toCharArray())
            res += Math.pow(26, N--) * (c - 'A' + 1);
        return res;
    }
    

    My solution is based on the idea like
    3234 = 3*10³ + 2*10² + 3*10^1 + 4*10^0

    But my question is, in my solution

    Math.pow(26, N--)
    

    the return type of this operation is double, while I am assigning the result to an int. But I am not getting any error using this code. I guess it is some kind of implicit type casting in Java that I am not very familiar with. Can anyone shed some light on me please? Thanks!


  • 1
    S

    It is because of += operator you are using.
    try splitting it out res = res + Math.pow(26, N--) * (c - 'A' + 1);
    and you should see compiler error.


  • 0

    @shp3431 Thanks for your reply. It helps me solve my problem!

    So here's what I found that cleared my confusions.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.