Hey-yo people!

Welcome to yet another edition (day 20) of my coding diary. I am sure, you might be having some thoughts about what I do here. So, every day I solve a challenge, sharing some interesting approaches + my learning.

Well, let's jump straight to the problem statement for the day!

**Problem of the day** - To Lower Case

**Tag** - Easy

Given a string `s`

, return the string after replacing every uppercase letter with the same lowercase letter.

**Example 1:**

**Input:** s = "Hello"

**Output:** "hello"

I don't even need to re-iterate the problem. It's the simple challenge one can ever get. Hold on, I know it can be solved within seconds but trust me, we are going to discuss some really cool insights.

I have a couple of solutions for this problem -

**The very first, simplest solution**

```
class Solution {
public:
string toLowerCase(string s) {
for(int i=0;i<s.length();i++) {
s[i] = tolower(s[i]);
}
return s;
}
};
```

I am sorry, don't punish me for using the built-in function.

**ASCII comes to rescue**

```
class Solution {
public:
string toLowerCase(string s) {
for(int i=0;i<s.length();i++) {
if(int(s[i]) >= 65 && int(s[i]) <= 90) s[i] += 32;
}
return s;
}
};
```

Pretty straightforward!

Tip for C++ beginners: Use int() to convert char to decimal and use char() to convert, a number to ASCII Char.

I usually, struggle to remember the exact ASCII code of `A`

, `Z`

,`a`

,`z`

. So, I did this -

```
class Solution {
public:
string toLowerCase(string s) {
for(int i=0;i<s.length();i++) {
if(s[i] >= 'A' && s[i] <= 'Z') s[i] += 32;
}
return s;
}
};
```

Ahh, Some times I don't even remember the difference is `32`

. So,

```
if(s[i] >= 'A' && s[i] <= 'Z') s[i] = s[i] - 'A' + 'a';
```

Here is the hilarious approach to optimize it further.

As, to optimize the comparison, instead of using -

```
if(s[i] >= 'A' && s[i] <= 'Z')
```

we can do,

```
if(s[i] <= 'Z' && s[i] >= 'A')
```

So, the thought is, for every lower case letter, it will get rejected in the first check itself, of the `if`

condition. One comparison saved! (drum rolls please)

I know I am being too picky here but that's how I optimized it further. Not to mention, my runtime beats 100% of the submissions.

One guy solved it using bit manipulation. Insane!

You might like previous editions of my coding diary

- Day #19 - N-Repeated Element in Size 2N Array.
- Day #18 - Count Negative Numbers in a Sorted Matrix.
- Day #17 - Sum of Unique Elements.
- Day #16 - Best Time to Buy and Sell Stock.
- Day #15 - Count Number of Pairs With Absolute Difference K.
- Day #14 - Minimum Number of Operations to Move All Balls to Each Box.

## Top comments (0)