• 8. String to Integer (atoi)


    此题不难,主要在于你能否考虑到多种细节情况,下面总结如下

    1.有空格  " 134 45"

    2.有符号  " + 23 4"  "- 234"

    3.有其他字符  "af+234"

    4.超出临界值  "9223372036854775809"

    代码如下:

     1     public static int atoi(String str) {
     2 
     3         if (str == null || str.trim().length() == 0) {
     4             return 0;
     5         }
     6         int i = 0;
     7 
     8         // 去空格
     9         str = str.trim();
    10         // 符号
    11         char flag = '+';
    12         if (str.charAt(0) == '-') {
    13             flag = '-';
    14             i++;
    15         } else if (str.charAt(0) == '+') {
    16             flag = '+';
    17             i++;
    18         } else if (str.charAt(0) >= '0' && str.charAt(0) <= '9') {
    19             flag = '+';
    20         } else {
    21             return 0;
    22         }
    23 
    24         // 计算
    25         double result = 0;
    26         while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
    27             result = result * 10 + (str.charAt(i) - '0');
    28             i++;
    29         }
    30 
    31         if (flag == '-') {
    32             result = -result;
    33         }
    34 
    35         if (result > Integer.MAX_VALUE) {
    36             result = Integer.MAX_VALUE;
    37         }
    38         if (result < Integer.MIN_VALUE) {
    39             result = Integer.MIN_VALUE;
    40         }
    41 
    42         return (int) result;
    43     }
  • 相关阅读:
    架构漫谈阅读笔记(1)
    第一周学习进度
    2月13号寒假总结
    2月12日寒假总结
    2月11日寒假总结
    2月10日寒假总结
    寒假学习进度笔记一
    mapreduce课上实验
    个人课程总结
    用户体验评价
  • 原文地址:https://www.cnblogs.com/imyanzu/p/5156973.html
Copyright © 2020-2023  润新知