Problem Statement
Given a character or a string in uppercase, convert it to its lowercase equivalent.
Constraints:
- Input may be a single character or a string of length
1 ⤠length ⤠10^5
. - Only ASCII characters are considered (
'A'
toāZā
).
Examples
Example 1:
Input: 'H'
Output: 'h'
Example 2:
Input: "HELLO"
Output: "hello"
Different Approaches
1ļøā£ Using Standard Library Function tolower()
C++ provides the lower()
function in <cctype>
that converts to its lowercase form if it's uppercase.
Code:
#include <iostream>
#include <cctype>
using namespace std;
string toLowercase(string str) {
for (char &ch : str) {
ch = tolower(ch);
}
return str;
}
int main() {
string input = "HeLLo123";
cout << toLowercase(input); // Output: hello123
}
Complexity Analysis:
- Time Complexity:
O(n)
- Space Complexity:
O(1)
2ļøā£ Using ASCII Conversion
Intuition:
In ASCII:
āAā
= 65,āaā
= 97 ā difference Ā = 32- To convert: add 32 to uppercase letters
Code:
#include <iostream>
using namespace std;
string toLowercase(string str) {
for (char &ch : str) {
if (ch >= 'A' && ch <= 'Z') {
ch = ch + 32;
}
}
return str;
}
int main() {
string input = "WORLD";
cout << toLowercase(input); // Output: world
}
Complexity Analysis:
- Time Complexity:
O(n)
- Space Complexity:
O(1)
3ļøā£ Using Bitwise Trick: ch | ā ā
Intuition:
In ASCII:
- BIt 5 distinguishes upper from lowercase.
- OR-ing with space (
' '
= 0x20) sets that bit.
Why It Works?
'A' = 65 -> 0100 0001
'a' = 97 -> 0110 0001
' ' = 32 -> 0010 0000
Notice:
'A' | ' ' = 01000001 | 00100000 = 01100001 = 'a'
So:
- Any uppercase letter
'A'
to'Z'
(ASCII 65ā90), when OR'ed with a space' '
, turns into its lowercase equivalent. - The space character (
' '
= 0x20) sets the 6th bit (bit at position 5, 0-indexed), which distinguishes lowercase from uppercase.
Limitation:
This only works correctly for uppercase alphabetic characters (AāZ).
For non-alphabetic characters, it might produce unintended results.
Code:
#include <iostream>
using namespace std;
string toLowercase(string str) {
for (char &ch : str) {
if (ch >= 'A' && ch <= 'Z') {
ch = ch | ' ';
}
}
return str;
}
int main() {
string input = "CPP";
cout << toLowercase(input); // Output: cpp
}
Complexity Analysis:
- Time Complexity:
O(n)
- Space Complexity:
O(1)