Here is my java solution


  • 32
    D

    Here is my Java solution. Similar to the number to title.

    public int titleToNumber(String s) {
        int result = 0;
        for(int i = 0 ; i < s.length(); i++) {
          result = result * 26 + (s.charAt(i) - 'A' + 1);
        }
        return result;
      }

  • 0
    I

    what is run time ?


  • 0
    D

    O(n) where n is characters in s


  • 3
    R

    This is neat. I looped from the end, had to use Math.pow(). Which seems unnecessary after looking at your solution.

    public class Solution {
        public int titleToNumber(String s) {
    
            int result = 0;
    
            for (int i = s.length() - 1, j = 0; i >= 0; i--, j++)
                result += Math.pow(26, j) * (s.charAt(i) - 'A' + 1);
    
            return result;
        }
    }

  • 0
    T

    @rainhacker I did it just like you. Do you think calling power is not as efficient as the darko1002001's algorithm?


  • 0
    G

    @darko1002001 yes,you did't use Math.pow(),that's great! this is my code:

    public class Solution {
        public int titleToNumber(String s) {
            s=s.toUpperCase();
            int count=0;
            int len=s.length();
            for(int i=0;i<len;i++){
                int curr=s.charAt(i)-64;
                count+=Math.pow(26,len-i-1)*curr;
            }
            return (int)count;
        }
    }
    

  • 0
    2

    why is it result*26 instead of adding 26? every time there's a new "digit" seems like should be result+26 i'm not understanding why it's multiply instead adding..


Log in to reply
 

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