Problem Statement
Given a character or string in lowercase, convert it to its uppercase equivalent.
Constraints:
- Input is a lowercase ASCII character or string.
1 ≤ length ≤ 10^5
Examples
Example 1:
Input: 'h'
Output: 'H'
Example 2:
Input: "hello123"
Output: "HELLO123"
Different Approaches
1️⃣Using Standard Library Function (toupper()
)
Intuition:
C++ provides the toupper()
function in <cctype>
to convert a character to uppercase.
Code:
#include <iostream>
#include <cctype>
using namespace std;
string toUppercase(string str) {
for (char &ch : str) {
ch = toupper(ch);
}
return str;
}
int main() {
string input = "hello123";
cout << toUppercase(input); // Output: HELLO123
}
Complexity Analysis:
- Time Complexity:
O(n)
- Space Complexity:
O(1)
2️⃣ Using ASCII Conversion
Intuition:
In ASCII:
'a'
= 97,'A'
= 65 → difference = 32- To convert: subtract 32 from lowercase letters
Code:
#include <iostream>
using namespace std;
string toUppercase(string str) {
for (char &ch : str) {
if (ch >= 'a' && ch <= 'z') {
ch = ch - 32;
}
}
return str;
}
int main() {
string input = "world";
cout << toUppercase(input); // Output: WORLD
}
Complexity Analysis:
- Time Complexity:
O(n)
- Space Complexity:
O(1)
3️⃣ Using Bitwise Trick: ch & ‘_’
Intuition:
In ASCII:
- Bit 5 distinguishes lowercase from uppercase.
- AND-ing with underscore
'_' = 0x5F
clears bit 5
Why It Works:
Char | Binary |
---|---|
'a' = 97 | 01100001 |
'A' = 65 | 01000001 |
'_' = 95 | 01011111 |
'a' & '_' = 'A' |
Code:
#include <iostream>
using namespace std;
string toUppercase(string str) {
for (char &ch : str) {
if (ch >= 'a' && ch <= 'z') {
ch = ch & '_'; // Bitwise trick
}
}
return str;
}
int main() {
string input = "cpp";
cout << toUppercase(input); // Output: CPP
}
Complexity Analysis:
- Time Complexity:
O(n)
- Space Complexity:
O(1)