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