LeetCode709-转换成小写字母

题目链接

英文链接:https://leetcode.com/problems/to-lower-case/

中文链接:https://leetcode-cn.com/problems/to-lower-case/

题目详述

实现函数 ToLowerCase(),该函数接收一个字符串参数 str,并将该字符串中的大写字母转换成小写字母,之后返回新的字符串。

示例 1:

1
2
输入: "Hello"
输出: "hello"

示例 2:

1
2
输入: "here"
输出: "here"

示例 3:

1
2
输入: "LOVELY"
输出: "lovely"

题目详解

  • 小写字母的 ASCII 码的范围为 97~122。
  • 大写字母的 ASCII 码的范围为 65~90。
  • 小写字母 -32 可以转换为大写字母。
  • 大写字母 +32 可以转换为小写字母。
  • 观察大小写字母的二进制形式,小写字母的第 6 位(从右往左数)为 1,大写字母的第 6 位(从右往左数)为 0,其余位均一致。
  • 据此,对字母的第 6 位置 1(| 0x20),可以得到它的小写形式;对字母的第 6 位置 0(& 0x5f),可以得到它的大写形式。
1
2
3
4
5
6
7
8
9
10
public class LeetCode_00709 {

public String toLowerCase(String str) {
char[] cs = str.toCharArray();
for (int i = 0; i < cs.length; ++i) {
cs[i] |= 0x20;
}
return new String(cs);
}
}

我们也可以直接调用 String 的 API。

1
2
3
4
5
6
public class LeetCode_00709 {

public String toLowerCase(String str) {
return str.toLowerCase();
}
}