Write a program or function that takes a string as input and converts all lowercase alphabetic characters (a-z) to their uppercase equivalents (A-Z). Non-alphabetic characters (such as digits, symbols, and spaces) and already uppercase letters should remain unchanged.
Input: "hello"
Output: "HELLO"
Explanation: All lowercase letters 'h', 'e', 'l', 'l', 'o' are converted to uppercase.
Input: "TcS NqT!"
Output: "TCS NQT!"
Explanation: Mixed case string: 'T' and 'S' remain uppercase, 'c' and 'q' and 't' are converted to 'C', 'Q', 'T', and '!' remains unchanged.
Input: "123abc DEF"
Output: "123ABC DEF"
Explanation: Digits '123' and space remain same, 'abc' converted to 'ABC', and 'DEF' already uppercase remains unchanged.
The key insight is that lowercase English letters (a-z) have ASCII values exactly 32 greater than their uppercase counterparts (A-Z). By checking if a character is in the range 'a' to 'z', we can convert it to uppercase by subtracting 32 from its ASCII value. All other characters remain unchanged.
#include <string>
using namespace std;
string convertToUpper(string s) {
for (char &c : s) {
if (c >= 'a' && c <= 'z') {
c -= 32;
}
}
return s;
}
public class Solution {
public static String convertToUpper(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 'a' && c <= 'z') {
sb.append((char)(c - 32));
} else {
sb.append(c);
}
}
return sb.toString();
}
}
def convert_to_upper(s):
result = []
for c in s:
if 'a' <= c <= 'z':
result.append(chr(ord(c) - 32))
else:
result.append(c)
return ''.join(result)
function convertToUpper(s) {
let result = '';
for (let i = 0; i < s.length; i++) {
let c = s[i];
if (c >= 'a' && c <= 'z') {
result += String.fromCharCode(c.charCodeAt(0) - 32);
} else {
result += c;
}
}
return result;
}
Time Complexity: O(n), where n is the length of the input string. Each character is processed exactly once.
Space Complexity: O(n) for the output string. In languages with immutable strings (Java, Python, JavaScript), a new string is constructed. In C++, we modify a copy of the input string, which also requires O(n) space.
Your notes are automatically saved in your browser's local storage and will persist across sessions on this device.