Tuesday, October 16, 2012

Multiply Strings

Visit this to view the content of this question.

Java code:

  public static String multiple(String num1, String num2)
    {
     String result = "";
    
     if (num1.isEmpty() || num2.isEmpty())
         return result;
     if ( num1.compareTo("0") == 0 || num2.compareTo("0") == 0)
         return "0";
    
     int tmp = 0, add = 0;
     int j;
    
     for (int i = 0; i < num1.length() + num2.length() - 1; i++)
     {
       if ( i >= num1.length() )
           j = num1.length() -1;
       else j = i;
          
       while ( (i - j) < num2.length() && j >= 0)
       {
           System.out.println(i + " " + j);
          
        tmp += Integer.parseInt(num2.substring(num2.length() -1 -i+j, num2.length() -i+j)) * Integer.parseInt(num1.substring(num1.length() - 1 - j, num1.length()- j));
        System.out.println(tmp);
        j--;
       }
      
       result =  (tmp + add)%10 + result;
       add = (tmp+add)/10;
       tmp = 0;
      
     }
     if (add != 0)
         result = add + result;
   
    
     return result;
    
    }


No comments:

Post a Comment