Why the running time is different between these two functions?


  • 1

    The first one runs at 2ms but the second one runs at 3ms. I cannot tell what is the difference between the two functions?

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

    public int titleToNumber3ms(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 also confused about the two:

    public class Solution {
        public int titleToNumber(String s) {
            int num = 0;
            int len = s.length();
            for(int i = 0; i < len; i++){
            	num = num * 26 + (int)(s.charAt(i) - '@');
            }
            return num;
        }
    }
    
    
    public class Solution {
        public int titleToNumber(String s) {
             int value = 0;
            for(int i = 0; i < s.length(); i++)
                value = value * 26 + ((int)s.charAt(i) - 'A') + 1;
            return value;
        }
    }
    

    the first runs 3 ms, but the second runs 2 ms.
    I cant tell the difference


Log in to reply
 

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