NC100 把字符串转换成整数(atoi)

落日映苍穹つ 2024-03-27 16:39 113阅读 0赞

牛客华为机试题库【题号 HJ开头】(重点看)
牛客在线编程算法篇【题号NC开头】
剑指offer【题号 JZ开头】
力扣

1)原题链接

2)已有题解

3)代码

  1. package string;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import static java.lang.System.in;
  6. /**
  7. * NC100 把字符串转换成整数(atoi)
  8. */
  9. public class NC100StringToInt {
  10. public static void main(String[] args) throws IOException {
  11. BufferedReader bf = new BufferedReader(new InputStreamReader(in));
  12. String str = bf.readLine();
  13. bf.close();
  14. int res = StrToInt(str);
  15. System.out.println(res);
  16. }
  17. /**
  18. * NC100 把字符串转换成整数(atoi)
  19. */
  20. public static int StrToInt(String s) {
  21. //空串
  22. if (s.isEmpty()) {
  23. return 0;
  24. }
  25. int length = s.length();
  26. int index = 0;
  27. //去掉前导空格,如果有
  28. while (index < length) {
  29. if (s.charAt(index) == ' ') {
  30. index++;
  31. } else {
  32. break;
  33. }
  34. }
  35. //去掉空格就什么都没有了
  36. if (index == length) {
  37. return 0;
  38. }
  39. int operator = 1;
  40. //处理第一个符号是正负号的情况
  41. if (s.charAt(index) == '+')
  42. index++;
  43. else if (s.charAt(index) == '-') {
  44. index++;
  45. operator = -1;
  46. }
  47. //去掉符号就什么都没有了
  48. if (index == length) {
  49. return 0;
  50. }
  51. int res = 0;
  52. while (index < length) {
  53. char chr = s.charAt(index);
  54. //后续非法字符,截断
  55. if (chr < '0' || chr > '9') {
  56. break;
  57. }
  58. // 处理越界
  59. // 因为如果越界被显示导致记错错误但是不会报错,所以这里才往前推判断出界
  60. // 基于公式res = res * 10 + operator * (chr - '0');
  61. // Integer.MAX_VALUE 2147483647
  62. // Integer.MAX_VALUE / 10 214748364
  63. // Integer.MAX_VALUE % 10 7
  64. // 如上值就会理解为何要如此判断
  65. if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && (chr - '0') > Integer.MAX_VALUE % 10)) {
  66. return Integer.MAX_VALUE;
  67. }
  68. // Integer.MAX_VALUE -2147483648
  69. // Integer.MAX_VALUE / 10 -214748364
  70. // Integer.MAX_VALUE % 10 -8
  71. if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && (chr - '0') > -(Integer.MIN_VALUE % 10))) {
  72. return Integer.MIN_VALUE;
  73. }
  74. res = res * 10 + operator * (chr - '0');
  75. index++;
  76. }
  77. return res;
  78. }
  79. }

发表评论

表情:
评论列表 (有 0 条评论,113人围观)

还没有评论,来说两句吧...

相关阅读