Convert Lowercase Letters to Uppercase
Solve this ProblemEasy5 min
Topics
BasicsStrings
Companies
TCSInfosysWipro
Given a string
text, return a copy in which every lowercase letter a–z is replaced by its uppercase version. All other characters stay the same.
This exercise shows how characters really work: each one is a number, and in ASCIIASCIIThe standard table that assigns codes 0–127 to English letters, digits, punctuation and control characters. the lowercase alphabet sits exactly 32 codes above the uppercase one. It also introduces immutable stringsImmutable StringA string that cannot be changed after creation; operations return new strings instead.: in Java, Python and JavaScript a converted string is always a new string.
Test Case 1:
Input:text = "Hello, World 2!"
Output:"HELLO, WORLD 2!"
Explanation:Lowercase letters change; capitals, digits, spaces and punctuation stay as they are.
Test Case 2:
Input:text = "abc"
Output:"ABC"
Explanation:Every letter changes.
Constraints
- ◆
1 ≤ text.length ≤ 200 - ◆
text contains printable ASCII characters
Try the Dry Run
Approach & Solutions
Shift Character Codes by 32Good
In ASCII, every lowercase letter's code is exactly 32 more than its uppercase partner: 'a' is 97 and 'A' is 65. So for each character in the range 'a'–'z', subtract 32 from its code; leave all other characters unchanged.
Time
O(n)Space
O(n)Java
class Solution {
public String toUpper(String text) {
char[] chars = text.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] >= 'a' && chars[i] <= 'z') {
chars[i] = (char) (chars[i] - 32);
}
}
return new String(chars);
}
}Built-in Upper-Case ConversionOptimal
Call the library: toUpperCase() in Java and JavaScript, upper() in Python, and toupper on each character in C and C++ (via transform in C++). They change letters only and leave every other character as it is.
Time
O(n)Space
O(n)Java
class Solution {
public String toUpper(String text) {
return text.toUpperCase();
}
}