Leetcode: To Lower Case (Kotlin)
Kotlin

Leetcode: To Lower Case (Kotlin)

December 13, 2024

Leetcode: To Lower Case (Kotlin)

This is an easy Linked List problem on Leetcode. I will go through my thought process for solving this in Kotlin. To Lower Case - LeetCode

Problem Statement

Examples

Constraints

Techniques to solve this problem

In this problem, you are given a string containing uppercase and lowercase letters and are asked to convert the string to lowercase.

  1. One possible approach is to iterate through the characters in the string and convert each uppercase character to lowercase by adding 32 to the current character.

  2. First, define the function to take a string as an argument and return a lowercase version of the string.

  3. Inside the function, iterate through the characters in the string and check if the character is uppercase by converting the character to an int and checking if it is bigger or equal to 65 (A) or less than or equal to 90 (Z). We can also specify the character directly. Both examples will be posted below.

  4. Convert each uppercase character to lowercase by adding 32 to the current character.

  5. When the loop is finished, call toString() on the StringBuilder object and return it.

Solutions

class Solution {
    fun toLowerCase(s: String): String {
        val sb = StringBuilder()
        // Iterate through the characters in the string
        for (c in s) {
            // Convert uppercase characters to lowercase by adding 32 to their ASCII value
            if (c.toInt() >= 65 && c.toInt() <= 90) {
                sb.append(c + 32)
            } else {
                sb.append(c)
            }
        }
        // Return the lowercase version of the string
        return sb.toString()
    }
}
class Solution {
    fun toLowerCase(s: String): String {
        val sb = StringBuilder()
        // Iterate through the characters in the string
        for (c in s) {
            // Convert uppercase characters to lowercase by adding 32 to their ASCII value
            if (c >= 'A' && c <= 'Z') {
                sb.append(c + 32)
            } else {
                sb.append(c)
            }
        }
        // Return the lowercase version of the string
        return sb.toString()
    }
}