码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode从零单排】No.8 String to Integer (丧心病狂的一道题)

时间:2015-02-07 11:43:19      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:leetcode   java   

题目

       题目很简单,就是写一个函数把string转换成int,但是通过率只有可怜的11%,难点是要考虑所有情况,特别是int溢出边界,反正我是写了2个小时还没解决,先放到这,有空接着搞,现在应该还有最后一个bug。

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 class Solution {
    public int atoi(String str) {
  		String num_str="";
        char[] str_char=str.toCharArray();
        char[] sympo="-+".toCharArray();
        boolean abs=true;
        for(int i=0;i<str.length();i++){
        	 if(str_char[i]==sympo[0] ||str_char[i]==sympo[1]){
        		 if(!Character.isDigit(str_char[i+1])){
        			 return 0;
        		 }
        		 if(str_char[i]==sympo[0]){
        			 abs=false;
        		 }
        	 }
      	  if(Character.isDigit(str_char[i])){       		 
   	   	      num_str+=String.valueOf(str_char[i]);      	   	 
   	        }
      	  else{
      		  if(num_str.length()!=0){
      			  break;
      		  }
      	  }
//       	  if(Character.isDigit(str_char[i])){       		 
//       	   	 num_str+=String.valueOf(str_char[i]);      	   	 
//       	    }
       	 if(num_str!=""){
       	   if(Math.abs(Integer.parseInt(num_str))>=Integer.MAX_VALUE / 10){
  		      return Integer.MAX_VALUE;
  	          }
       	   }
       }
        if(num_str!=""){
        	 if(abs){
        		 return Integer.parseInt(num_str);
        		 }
        	 else{
        		 return -Integer.parseInt(num_str);
        	 }
	    }
        else{
        	   return 0;
        
  }
    
 }
    
}



/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/


【LeetCode从零单排】No.8 String to Integer (丧心病狂的一道题)

标签:leetcode   java   

原文地址:http://blog.csdn.net/buptgshengod/article/details/43602071

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!