2015-02-18 4 views
0

Итак, я пытаюсь написать метод умножения, который умножает два больших положительных целых числа с использованием метода добавления (уже предварительно написанного внутри класса). Моя самая большая проблема прямо сейчас заключается в том, как добавить нули в конец с помощью моего вспомогательного метода (который добавляет первое число число раз от 0-9 (например, 12 * 6 будет добавлять 12 шесть раз). получите эту ценность, я хочу добавить ее в 12 * 2, которая должна быть добавлена ​​с нулем (например, умножением начальной школы более или менее). Я нарисовал стрелки, относящиеся к рассматриваемым методам. У кого-нибудь есть предложения или идеи?, умножая два больших целых числа с использованием метода добавления и добавляющих нулей

12 
x 26 
---- 
    72 
240 <- how to append this zero? 
---- 
312 

Вот мой класс:

public class BigNum { 

// F i e l d s 

private String num; // Representation of our number 

// C o n s t r u c t o r s 

/** Constructs a <tt>BigNum</tt> from a non-empty String of digits. 
* @param num The string to be interpreted. 
* @throws IllegalArgumentException if num is length zero or 
*  has any non-numeric digits 
* @throws NullPointerException if num is null 
*/ 
public BigNum(String num) { 
    for (int i=0; i<num.length(); i++) { 
     if (! Character.isDigit(num.charAt(i))) { 
      throw new IllegalArgumentException(); 
     } 
    } 
    if (num.length() == 0) { 
     throw new IllegalArgumentException(); 
    } 
    this.num = num; 
} 

/** Constructs a <tt>BigNum</tt> from a non-negative integer. 
* @param num The non-negative integer to be interpreted. 
* @throws IllegalArgumentException if num is negative 
*/ 
public BigNum(int num) { 
    // If num<0, redirected constructor will throw exception due to "-" 
    this(""+num); 
    if(num < 0) { 
     throw new IllegalArgumentException(); 
    } 
    //this(""+num); 
} 

/** Constructs a <tt>BigNum</tt> with value zero. 
*/ 
public BigNum() { 
    num="0"; 
} 

// P u b l i c M e t h o d s 

/** Adds two <tt>BigNum</tt> objects' values together and returns a new 
    * <tt>BigNum</tt> object with the resulting value. 
    * 
    * @param other this and other objects get added together 
    * @return a new BigNum with the resulting value 
    */ 
public BigNum add(BigNum other) { 
    // Make shorter refer to the shorter num, longer to the longer num 
    String shorter = other.num; 
    String longer = this.num; 
    if (this.num.length() < other.num.length()) { 
     shorter = this.num; 
     longer = other.num; 
    } 
    // Prepend zeros to make shorter as long as longer 
    while (shorter.length() < longer.length()) { 
     shorter = "0" + shorter; 
    } 
    // Add columns like we did in grade school 
    int carry = 0; 
    String result = ""; 
    for (int i=shorter.length()-1; i>=0; i--) { 
     int temp = Character.getNumericValue(shorter.charAt(i)) + 
        Character.getNumericValue(longer.charAt(i)) + carry; 
     result = (temp%10)+result; 
     carry = temp/10; 
    } 
    // Handle carry-out, if there is one. Return result 
    if (carry == 1) { 
     result = "1"+result; 
    } 
    return new BigNum(result); 
} 

/**Multiplies two <tt>BigNum<tt> values together and returns a new 
    *<tt>BigNum<tt> object with the resulting value. 
    * 
    *@param other 
    *@returns a new BigNum with resulting value 
    */ 
public BigNum mult(BigNum other) { //<---------------------Method in question 
    BigNum result = new BigNum(); 
    String s = ""; 
    int current = 0; 
    for(int i=0; i < this.num.toString().length();i++) { 
    current += Character.getNumericValue(this.num.charAt(i)); 
    result = mult(current,other); 
    s = result.toString(); 
    int count=0; 
    for(int j=0; j < count; j++) { 
     s += "0"; 
     count++; 
    } 
    } 
    return new BigNum(s); 
} 

/**Helper method that adds the other value a set of number of times, 0-9 
    * 
    *@param and int n and other object 
    *@returns resulting value 
    */ 
public BigNum mult(int n, BigNum other) { //<---------------Method in question 
    BigNum result = new BigNum(); 
    for(int i=0;i < n;i++) { 
     result=result.add(other); 
    } 
    return result; 
} 

/**Compares the other object with another value and only returns true if 
    *the value is less than the object the value. 
    * 
    *@param other 
    *@return true or false 
    */ 

public boolean less(BigNum other) { 
    String shorter = other.num; 
    String longer = this.num; 
    if(other.toString().length() > this.toString().length()) { 
     return true; 
    } 
    else if(other.toString().length() == this.toString().length()){ 
     for(int i=0; i < other.toString().length();i++) { 
      if(Character.getNumericValue(shorter.charAt(i)) > Character.getNumericValue(longer.charAt(i))){ 
       return true; 
      } 
     } 

    } 
    return false; 
} 

/** Returns a string representation of the number. No leading zeros 
    * will exist unless the overall value is zero. 
    * 
    * @return String representation of the BigNum 
    */ 
public String toString() { 
    return num; 
} 

/** Used only for unit testing. When run, should output only trues. */ 
public static void main(String[] args) { 
    // Test constructors 
    BigNum test = new BigNum("123"); 
    System.out.println(test.toString().equals("123")); 
    test = new BigNum(123); 
    System.out.println(test.toString().equals("123")); 
    test = new BigNum(); 
    System.out.println(test.toString().equals("0")); 
    // Test addition 
    BigNum a = new BigNum(); 
    BigNum b = new BigNum(); 
    BigNum c = a.add(b); 
    System.out.println(c.toString().equals("0")); 
    a = new BigNum("999"); 
    b = new BigNum("101"); 
    c = a.add(b); 
    System.out.println(c.toString().equals("1100")); 
    a = new BigNum("237468273643278"); 
    b = new BigNum("87326487236437826"); 
    c = a.add(b); 
    System.out.println(c.toString().equals("87563955510081104")); 
    //Test multiplication 
    BigNum j = new BigNum(); 
    BigNum k = new BigNum(); 
    BigNum l = j.mult(k); 
    j = new BigNum("111"); 
    k = new BigNum("3");   
    l =j.mult(k); 
    System.out.println(l.toString()); 
    System.out.println(j.less(k)); 

} 

}

+0

Полный код, относящийся к вашему вопросу? Общее решение для добавления 0 в правую часть числа - это умножить его на 10 ... –

+0

Наверное, нет, но это не помешает. Что касается решения, как именно я могу его добавить после второго умножения/итерации, я подумал об использовании цикла for, но я не мог понять, с чего начать или разместить его. – user4147933

ответ

0

Умножьте первое число с каждым символом второго числа, а затем снова умножьте результат на 10 (или в зависимости от его позиции, т. Е. 10 для позиции десятков, 100 для сотен позиции и т. Д.) Для добавления нулей.

 Смежные вопросы

  • Нет связанных вопросов^_^