Help, I cannot figure out why this simple Error happens ...


  • 0
    N

    Hi, could anyone help me with this?

    I have no idea why my code fails due to following error:

    Input:
    "9133", "0"
    Output:
    "0000"
    Expected:
    "0"

    Obviously, the first if-condition will return "0" if any one of inputs is "0". And I also tried on Eclipse, it worked well. No sure why it failed on LC?

    Thanks!

       public String multiply(String num1, String num2) {
            if (num1 == "0" || num2 == "0") {
                return "0";
            }
            
        	StringBuilder result = new StringBuilder();
            
            char[] str1 = new StringBuffer(num1).reverse().toString().toCharArray();	
            char[] str2 = new StringBuffer(num2).reverse().toString().toCharArray();
            
            int[] d = new int[num1.length()+num2.length()];
            
            for (int i = 0 ; i < str1.length; i++) {
            	for (int j = 0; j <str2.length; j++) {
            		d[i+j] += (str1[i]-'0') * (str2[j]-'0');
            	}
            }
            
    
            int carry = 0;
            
            for (int i = 0; i < d.length; i++) {
            	
            	int digit = (d[i]+ carry)%10;
            	result.append(digit);
            	carry = (d[i]+carry)/10;
    
            }
            
            result.reverse();
    
            if (result.charAt(0) == '0') {
            	
            	result.deleteCharAt(0);
            }
            
             return result.toString();
        }

  • 1

    Obviously, the first if-condition will return "0" if any one of inputs is "0"

    Not if the "0" strings are different objects.

    You need to compare strings with .equals(...), not with ==.


  • 0
    N

    thanks! i forgot that "==" only compares reference not value!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.