2017-10-18 7 views
-1

私はLeetCode問題逆整数のコードを書いています。私は自分の解決策に間違いがないのを見つけることはできませんが、LeetCode公式サイトでそれを実行すると、このランタイムエラーが伝播します。この問題を解決するにはjava.lang.NumberFormatException:入力文字列の場合: ""自分のコードに基づいていますか?

class Solution { 
    public int reverse(int x) 
    { 
     String resultStr = ""; 
     int result = 0; 
     boolean isNegative = false; 
     if(x < 0) 
     { 
      isNegative = true; 
     } 
     int integer = Math.abs(x); 
     int divid = integer; 
     while(divid!= 0) 
     { 
      divid = divid/10; 
      resultStr += integer%10; 
      integer = divid; 
     } 
     result = Integer.parseInt(resultStr); 
     if(isNegative) 
     { 
      result = 0-result; 
     } 
     return result; 
    } 
} 
+4

あなたは 'resultStr.equals( "")' '場合int'にそれを解析する前にチェックする必要があります。 'divid'が' 0'の場合、 'resultStr'は空のままです。 – BackSlash

+0

良いキャッチ。ありがとう。 – user7027796

答えて

-1
class Solution { 
    public int reverse(int x) { 
     String resultStr = ""; 
     int result = 0; 
     boolean isNegative = x < 0; 
     int integer = Math.abs(x); 
     int divid = integer; 
     while(divid!= 0) { 
      divid = divid/10; 
      resultStr += integer%10; 
      integer = divid; 
     } 
     if (!resultStr.equals("")) { 
      result = Integer.parseInt(resultStr); 
      if(isNegative) { 
       result = 0-result; 
      } 
     } 
     return result; 
    } 
} 
-1

この問題の最終的な解決策:

class Solution { 
public int reverse(int x) 
{ 
    String resultStr = ""; 
    int result = 0; 
    boolean isNegative = false; 
    if(x < 0) 
    { 
     isNegative = true; 
    } 
    int integer = Math.abs(x); 
    int divid = integer; 
    while(divid!= 0) 
    { 
     divid = divid/10; 
     resultStr += integer%10; 
     integer = divid; 
    } 
    if(resultStr.equals("")) 
    { 
     return 0; 
    } 
    else 
    { 
     try 
     { 
      result = Integer.parseInt(resultStr); 
      if(isNegative) 
      { 
       result = 0-result; 
      } 
      return result;    
     } 
     catch(Exception e) 
     { 
      return 0; 
     } 
    } 
} 

}

関連する問題