LeetCode算法题之第8题String to Integer (atoi)

Question:

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

解决:

将字符串变为数字。需要注意坑很多。

public int myAtoi(String str) {
    int sum = 0;
    int flag = 1;
    str = str.trim();
    int i = 0;
    if (str.length() == 0)
        return sum;
    if (str.charAt(0) == '-' || str.charAt(0) == '+'){
        if (str.charAt(0) == '-')
            flag = -1;
        ++i;
    }
    while(i < str.length() && Character.isDigit(str.charAt(i))){
        if (judge(flag, sum, str.charAt(i)-'0')){
            if (flag == 1)
                sum = Integer.MAX_VALUE;
            else
                sum = Integer.MIN_VALUE;
            break; 
        }
        sum = sum * 10 + (str.charAt(i) - '0');
        ++i;
    }
    return flag == 1 ? sum : -sum;
}
public boolean judge(int flag, int sum, int digit){
    boolean result = false;
    if (flag == 1 && (sum > Integer.MAX_VALUE/10 || sum == Integer.MAX_VALUE/10 && digit > Integer.MAX_VALUE%10))
        result = true;
    if (flag == -1 && (-sum < Integer.MIN_VALUE/10 || -sum == Integer.MIN_VALUE/10 && -digit < Integer.MIN_VALUE%10))
        result = true;
    return result;
}

代码地址(附测试代码):
https://github.com/shichaohao/LeetCodeUsingJava/tree/master/src/stringToInteger

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,471评论 0 23
  • 文/月中山 上一章 / 简介+目录 /下一章 “冬姐,你明天要上班了吗?” 孟杰跟姐姐睡下铺,表姐睡上铺,晚上...
    月中山阅读 1,768评论 9 5
  • 青春的少女怕生存真是荒谬吧,我对自己没有信心,对无法预知的未来充满恐惧,我害怕过不上自己想要的人生 如果失败了就去...
    Hahaha1223阅读 1,612评论 0 0
  • 知吾者知吾之所泣, 爱吾者吾泣之所泣。 嘲吾者吾泣之所讽, 恨吾者吾泣之所喜。
    说一条阅读 1,846评论 0 1
  • 上帝安排了一些人,注定在教会我们什么后离开。他放下未饮完的杯盏背起行囊离开客栈,转身就是好多年,却要我拿一生去缅怀...
    阿伦喵唔阅读 1,079评论 0 0