leetcode Problem8_StringtoInt

来源:互联网 发布:菜鸟裹裹抢单软件 编辑:程序博客网 时间:2024/06/01 08:35

Implement atoi to convert a string to an integer.

思路:本题的题目本身比较简单,但是case非常的多

比如:

1  "+"

2  " +-12"

3  "  0012a45"

4 溢出

等等,本题的重点就在于处理这些case。下面代码(已经通过lootcode)

今天就刷到这,保持基本每天4题的速度

public class Solution {
   public int myAtoi(String str) {
    String strr=str.trim();
    int loc=strr.length();
    if(strr.equals("-")|| strr.equals("+")) return 0;
    if(strr==null || strr.length()==0) return 0;
    if(strr.charAt(0)=='-' || strr.charAt(0)=='+' ) {
    for(int i=1;i<strr.length();i++) {
    if(strr.charAt(i)>'9' || strr.charAt(i)<'0' && strr.charAt(i)!='+' && strr.charAt(i)!='-' ) {
    loc=i;
    break;
    }
    }
   
    }
    else {
    if(strr.charAt(0)<'0' || strr.charAt(0)>'9'  ) {
    return 0;
    }
    else {
    for(int i=1;i<strr.length();i++) {
    if(strr.charAt(i)>'9' || strr.charAt(i)<'0') {
    loc=i;
    break;
    }
    }
    }
    }
    if(loc==0) return 0;
//System.out.println(loc);
    int res=0;
    try{
    res=Integer.parseInt(strr.substring(0,loc));
    return res;
    } catch(NumberFormatException e) {
    if(Integer.parseInt(strr.substring(0,loc))>2147483647) return 2147483647;
    if(Integer.parseInt(strr.substring(0,loc))<-2147483648) return -2147483648;
   
    }
    return res;
   }
}

0 0
原创粉丝点击