如何解决这个java.lang.NumberFormatException:对于输入字符串:""基于我的代码?

时间:2017-10-18 19:42:19

标签: java runtime numberformatexception

我编写了LeetCode问题Reverse Integer的代码。我无法找到我的解决方案有什么问题,但在LeetCode官方网站上运行它时会传播此运行时错误。

   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;
    }
}

1 个答案:

答案 0 :(得分:-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;
        }
    }
}

}