重慶網(wǎng)站聯(lián)盟鄭州競(jìng)價(jià)代運(yùn)營(yíng)公司
1.轉(zhuǎn)換成小寫字母
原題:力扣709.
字符串大寫轉(zhuǎn)小寫有現(xiàn)成的API使用,但是我們也可以自己來實(shí)現(xiàn)。
使用或運(yùn)算進(jìn)行加操作能提高效率,因?yàn)?32 對(duì)應(yīng)的二進(jìn)制表示為 00100000 ,而大寫字母的范圍 [65, 90] 的二進(jìn)制表示在 00100000 的為 1 的位置均為 0 ,所以直接或操作就可以實(shí)現(xiàn)和加 32 一樣的效果。
class Solution {public String toLowerCase(String s) {StringBuilder sb = new StringBuilder();for (int i = 0; i < s.length(); i++) {char ch = s.charAt(i);if (ch >= 65 && ch <= 90) {ch |= 32;}sb.append(ch);}return sb.toString();}
}
2.字符串轉(zhuǎn)換整數(shù)(atoi)
原題:力扣8.
用 index 遍歷字符串?dāng)?shù)組。
public int myAtoi(String str) {int len = str.length();char[] charArray = str.toCharArray();int index = 0;while (index < len && charArray[index] = ' ') {index++;}if (index == len) {return 0;}int sign = 1;char firstChar = charArray[index];if (firstChar == '+') {index++;} else if (firstChar == '-') {index++;sign = -1;}int res = 0;while (index < len) {char currChar = charArray[index];if (currChar > '9' || currChar < '0') {break;}// 處理溢出情況if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && (currChar - '0') > Integer.MAX_VALUE % 10)) {return Integer.MAX_VALUE;}if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && (currChar - '0') > -(Integer.MIN_VALUE % 10))) {return Integet.MIN_VALUE;}// 為了便于處理溢出情況,每次給 res 賦值都帶 sign ,保證 res 的正負(fù)性res = res * 10 + sign * (currChar - '0');index++;}return res;
}
如果對(duì)您有幫助,請(qǐng)點(diǎn)贊關(guān)注支持我,謝謝!?
如有錯(cuò)誤或者不足之處,敬請(qǐng)指正!?
個(gè)人主頁(yè):星不易 ?
算法通關(guān)村專欄:不易|算法通關(guān)村 ?