Question:

Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.

Example:

  1. Input: "Hello"
  2. Output: "hello"
  1. Input: "here"
  2. Output: "here"
  3. Input: "LOVELY"
  4. Output: "lovely"

Solution:

  1. /**
  2. * @param {string} str
  3. * @return {string}
  4. */
  5. var toLowerCase = function(str) {
  6. // ASCII 编码大写小写相差32
  7. let arr = str.split('');
  8. let AscCode;
  9. let maxCode = 'Z'.charCodeAt();
  10. let minCode = 'A'.charCodeAt();
  11. for (let i = 0; i < arr.length; i++) {
  12. // 转换为ASCII码
  13. AscCode = arr[i].charCodeAt();
  14. // 大写字母,转小写
  15. if (maxCode >= AscCode && minCode <= AscCode) {
  16. arr[i] = String.fromCharCode(AscCode+32);
  17. }
  18. }
  19. return arr.join('');
  20. };

Runtime: 48 ms, faster than 100.00% of JavaScript online submissions for To Lower Case.