lintcode【入门】大小写转换

大小写转换

Python

class Solution:
    """
    @param character: a character
    @return: a character
    """
    def lowercaseToUppercase(self, character):
        # write your code here
        new_char = character.upper()
        return new_char

耗时101ms

大小写字母的ASCII码相差32 (小写-大写=32)
python中ord()函数,将字母转换位ASCII码;chr()函数,将ASCII码转换为字母

class Solution:
    """
    @param character: a character
    @return: a character
    """
    def lowercaseToUppercase(self, character):
        # write your code here
        return(chr(ord(character)-32))

C++

class Solution {
public:
    /**
     * @param character: a character
     * @return: a character
     */
    char lowercaseToUppercase(char character) {
        // write your code here
        char new_char = toupper(character);
        return new_char;
    }
};

耗时50ms

class Solution {
public:
    /**
     * @param character: a character
     * @return: a character
     */
    char lowercaseToUppercase(char character) {
        // write your code here
        return toupper(character);
    }
};

直接return大写转换会更快,耗时8ms
但python的耗时并不会收到影响

在c++中,ASCII码和字母的转换可通过系统默认的隐式转换,不需要加以声明就可以进行的转换

class Solution {
public:
    /**
     * @param character: a character
     * @return: a character
     */
    char lowercaseToUppercase(char character) {
        // write your code here
        int number = character-32;
        char new_char = number;
        return new_char;
    }
};

耗时50ms

你可能感兴趣的:(lintcode,lintcode,python,c++)