709. To Lower Case
阿新 • • 發佈:2019-02-10
uri 小寫 urn 得到 The public input amp 差值
Algorithm
to-lower-case
https://leetcode.com/problems/to-lower-case/
1)problem
Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase. Example 1: Input: "Hello" Output: "hello" Example 2: Input: "here" Output: "here" Example 3: Input: "LOVELY" Output: "lovely"
2)answer
聲明一個新的字符串變量,對傳入的字符串的字符逐個讀取,如果是大寫字母就取小寫與大寫之間的差值,得到大寫字符對應的小寫字母ASCII碼存進字符串中。處理完後返回結果。
3)solution
Cpp:
#include <stdio.h> #include <string> using std::string; class Solution { public: string toLowerCase(string str) { string re_val = ""; for (char str_val : str) { if (str_val >='A'&& str_val <='Z') { // 取小寫與大寫之間的差值,得到字符對應的小寫ASCII碼對應是什麽存進字符串中 re_val += (str_val + ('a' - 'A')); } else { // 如果是小寫就不處理 re_val += str_val; } } return re_val; } }; int main() { // 使用內容 Solution nSolution; nSolution.toLowerCase("hello World?"); return 0; }
Python:
class Solution(object): def toLowerCase(self, str): """ :type str: str :rtype: str """ ret = "" for s in str: if s>='A' and s<='Z': ret += chr(ord(s)+(ord('a')- ord('A'))) else: ret +=s return ret
709. To Lower Case