https://leetcode.com/problems/to-lower-case/
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"
https://leetcode.com/problems/to-lower-case/discuss/148993/Java-no-library-methods
I am assuming the whole point is to avoid
String#toLowerCase()
and Character#toLowerCase()
methods public String toLowerCase(String str) {
char[] a = str.toCharArray();
for (int i = 0; i < a.length; i++)
if ('A' <= a[i] && a[i] <= 'Z')
a[i] = (char) (a[i] - 'A' + 'a');
return new String(a);
}
You can speed up your conversion with a bitwise Or with 32. (5th bit). No if statement and faster than adding or subtracting.
public String toLowerCase(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = (char)(str.charAt(i) | (char)(32));
sb.append(c);
}
return sb.toString();
}