LeetCode --- --- series string converted to lowercase

Converted to lowercase

topic

Implementing a function toLowerCase (), the function takes a string str parameter

and the string is converted to uppercase lowercase, and then returns the new string.


Examples

示例 1:

输入: "Hello"
输出: "hello"
示例 2:

输入: "here"
输出: "here"
示例 3:

输入: "LOVELY"
输出: "lovely"

Source: stay button (LeetCode)

link: https://leetcode-cn.com/problems/to-lower-case/

copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.


Problem-solving ideas

1、使用 JavaScript 原生提供的转换小写 API, string.toLowerCase()

or

1、
使用字符编码对应的数值位差
`大写字符` A-Z 对应的是 65 - 90
`小写字符` a-z 对应的是 97 - 122
A 与 a 的数值位差为 32

2、
定义一个变量 lowerstr = ''
循环遍历字符串 `chars`
使用 char.charCodeAt() 拿到字符 char 对应的数值 strNum ,
判断是否处于 A-Z , 即 65 - 90 之间;
若是,则使用 String.fromCharCode(strNum + 数值位差) 拿到对应的 `小写字符`, 使用 lowerstr 进行拼接
若不是,直接使用 lowerstr 进行拼接

answer

let toLowerCase = function(str) {
    return str.toLowerCase()
};

or

let toLowerCase = function(str) {
    let lowerstr = ''
    // 循环遍历字符串 `str`
    for (let i = 0; i < str.length; i++) {
        // 使用 char.charCodeAt() 拿到字符 char 对应的数值 strNum 
        let strNum = str[i].charCodeAt()
        // 判断是否处于 A-Z , 即 65 - 90 之间;
        if (strNum >= 65 && strNum <= 90) {
            // 使用 String.fromCharCode(strNum + 数值位差) 拿到对应的 `小写字符`
            lowerstr += String.fromCharCode(strNum + 32)
        } else{
            lowerstr += str[i]
        }
    }
    return lowerstr
};

Guess you like

Origin www.cnblogs.com/linjunfu/p/12638486.html