2013-11-23 2 views
0

Я строю объекты с большими целыми числами и добавляю их вместе. Проблема в том, что я не знаю, как точно ее кодировать. Я создаю объект со значением 123456789, затем я создаю второй объект методом глубокой копии со значением 123456789. Мне нужно пройти и добавить каждую цифру от младшей значащей цифры до самой значащей цифры. Это мой код логически для меня.
Я уже создал один большой номер 123456789, мне нужно его скопировать, что я сделал. Тогда я должен добавить вместе два bigNumber вДобавление значений больших цифр

This is my main method 

public static void main(String[] args) { 
BigNumber b1 = new BigNumber(); 
    for (int i=9; i>=1; i--) 
    { 
     b1.addDigit(i); 
    } 
    System.out.println("b1 is " + b1.toString()); //return 123456789; corrent 

BigNumber b2 = new BigNumber(b1); //Creates a deep copy of b1 123456789 
System.out.println("b2: " + b2.toString()); //return 123456789 
System.out.println(b1.add(b2).toString()); //should return 123456789 + 123456789 = 246913578 
} 

Это мой метод добавить

public BigNumber add(BigNumber otherNum) 
{ 

     BigNumber newNum = new BigNumber(); // Create the new Number 
     BigNumber secNum = new BigNumber(); // 
     DigitNode temp = head; 
     while (temp != null) { //while loop to set the numbers 123456789 
      secNum.addDigit(temp.getDigit()); 
      temp = temp.next; 
     } 

     //At this I'm lost. I need to somehow get b1.. then get add it to my secNum that I made to 123456789, and put that into newNum and return it.. 
} 

ответ

1

Вы можете иметь дело с ними, как струны. Однако вы должны позаботиться о многом из того, что я написал в качестве комментариев:

public class LongIntegersAritymetic { 

// MAKE SURE TO CHECK THE SIGNS OF BOTH NUMBERS 
// 4 SITUATIONS: 
/* num1 + and num2 + =====> add 
* num1 + and num2 - =====> remove the sign from num2 
* and call substract(num1, num2_without_sign) 
* num1 - and num2 + =====> remove the sign from num1 
* and call substract(num2, num1_without_sign) 
* num1 - and num2 - =====> remove the sign from num1 and num2 
* and call add(num1_without_sing, num2_without_sign) 
* finally add the - sign to result*/ 


private static boolean changeResultSign = false; 



public static String add(String num1, String num2) { 

    String result = ""; 

    int n1 = 0, n2 = 0, res = 0, minLength = 0, carry = 0, maxLength = 0; 

    if(num1 != null & num2 != null) { 
      // num1 + and num2 + =====> add default 
     // num1 - and num2 - =====> remove the sign from num1 || solved! 
     ////and call add(num1_without_sing, num2_without_sign) || solved! 
     if(num1.charAt(0) == '-' & num2.charAt(0)== '-'){ 
      num1 = num1.substring(1); 
      num2 = num2.substring(1); 
      changeResultSign = true; 
     } 
     // num1 - and num2 + =====> remove the sign from num1 || solved! 
     //and call add(num1_without_sing, num2) || solved! 
    else if(num1.charAt(0)=='-'){ 
     num1 = num1.substring(1); 
     String a = subtarct(num2,num1); 
     return a; 
    } 
    // num1 + and num2 - =====> remove the sign from num2 ||solved! 
    //and call substract(num1, num2_without_sign) ||solved! 
    else if(num2.charAt(0)=='-'){ 
     num2 = num2.substring(1); 
     String b = subtarct(num1,num2); 
     return b; 
    } 
    if(checkDigits(num1) & checkDigits(num2)) { 
    minLength = Math.min(num1.length(), num2.length()); 
    maxLength = Math.max(num1.length(), num2.length()); 
    for(int i = 0; i < minLength; i++) { 
     n1 = num1.charAt(num1.length()-1-i) - '0'; 
     n2 = num2.charAt(num2.length()-1-i) - '0'; 
     res = (n1 + n2 + carry) % 10 ; 
     carry = (n1 + n2 + carry)/10; 
     // (new Integer(res)).toString(); 
     result = res + result ; // CHECK THE VALIDITY OF THIS!!! 
    } 
    for(int i = minLength; i < maxLength; i++) { 
     if(num1.length() > num2.length()) { 
      n1 = num1.charAt(num1.length()-1-i) - '0'; 
      res = (n1 + carry) % 10 ; 
      carry = (n1 + carry)/10; 
      result =res + result ; // CHECK THE VALIDITY OF THIS!!! 
     } 
     else { 
      n2 = num2.charAt(num2.length()-1-i) - '0'; 
      res = (n2 + carry) % 10 ; 
      carry = (n2 + carry)/10; 
      result = res+ result ; // CHECK THE VALIDITY OF THIS!!! 
     } 
     } 
     if(carry == 1) 
     result = carry +result ; // CHECK THE VALIDITY OF THIS!!! 
    } // End of if for valid digit Strings 
    else 
     throw new IllegalArgumentException("Invalid numbers!"); 
    } 
    else 
    throw new NullPointerException("Missing number(s)!"); 
return result ; 
} 



public static boolean checkDigits(String num) { 
    boolean a = true; 
    if(num != null) { 
     for(int i = 0; i < num.length(); i++) { 
     if(num.charAt(i) < '0' | num.charAt(i) > '9') 
      a = false; 

     } 
     return a; } 
    else 
    throw new NullPointerException("Missing number(s)!"); 
    } 



public static void main (String[] args){ 
    System.out.print(add("8437598745","8437598745")); 
}} 
+0

Это вообще идея? – user3011391

+0

Теперь я понимаю. Спасибо! – user3011391

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