1.转换成小写字母
思路:ASCll码中,a-z:97-122 A-Z:65-90
小写转大写-32,大写转小写+32
class Solution {public String toLowerCase(String s) {int len = s.length();StringBuilder str = new StringBuilder();for(int i = 0;i<len;i++){char c = s.charAt(i);if(c >= 'A' && c <='Z'){c += 32;}str.append(c);}return str.toString();}
}
2.字符串转换整数
思路:判断各种边界值,res直接*10会溢出,需要进行大小判断,如何判断?
一般res*10>max说明越界,转换一下res>max/10说明越界
但是这里有个问题如果一个数字为2147483648,res == max/10
这时需要(max-str[i]) / 10,如果res的最后一位数大于7,那么res>max/10
class Solution {public int myAtoi(String s) {char[] str = s.toCharArray();int sign = 1;int res = 0;int loop = 0;int max = Integer.MAX_VALUE;for(int i = 0;i<str.length;i++){if(loop == 1 && (str[i] == '-' || str[i] == '+'||str[i] == ' ')){break;}if(str[i]=='-'){sign = -1;loop = 1;continue;}if(str[i] == '+'){loop =1;continue;}if(str[i] != ' ' && (str[i]<'0' || str[i] >'9')){break;}if(str[i]>='0' && str[i] <='9'){int d = str[i] - '0';if(sign == 1 && (max- d)/10< res){return max;}if(sign == -1 && (max - d) / 10 < res){return -max - 1;}res = res*10 + d;loop = 1;}}return res*sign;}
}