Leetcode: String to Integer (atoi)

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 static int reverse(String str) {
		 String s = str.trim();
	        int length = s.length();
	        if(length == 0){
	            return 0;
	        }
		     boolean isPositive = true;
		     int i = 0;
	         if(s.charAt(i)=='-'||s.charAt(0)=='+'){
	        	 if(s.charAt(0)=='-'){
	        	 isPositive = false;
	        	 i++;
	        	 }else {
	        	     while(s.charAt(++i)=='+'){       	    	 
	        	     }
	        	     if(s.charAt(i)=='-'){
	    	        	 isPositive = false;
	    	        	 i++;
	        	     }
	        	 }
	        	
	         }
	         long revResult = 0;
	         while(i < length){
	        	 if(s.charAt(i)!= ' '){
	        		 revResult = revResult*10 + s.charAt(i)-'0';
	        	 }
	        	 i++;
	         }
	         if(isPositive == false){
	        	 revResult = -revResult;
	         }
		     return (int)revResult;
	    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章