My own BigInteger class. Need help.
First of all I want to say hello to all of you. It is my first post here. I am 19-year old student from Poland. My name is Artur.
So, my uni teacher gave me a project to made, which is not so hard as i thought, but still gives me some trouble.
I have to write a class, which can make operations on numbers, which are much longer than any type of variables. The only solution to make operations on such numbers is, save them as a String. It should look like BigInteger class, but when i started to read this class, i recognised i can not just copy from the documentation. I have to writte it myself.
Firstly i thought about :
User gives me String number one.
User gives me String number two.
Method add
Convert both Strings to CharArray
Make a simple adding from CharArrayOne[0] and CharArrayTwo[0] and save it to CharArrayThree[0] .
But then, when i add 2 chars, and the result is > 10, the char takes a form of ( ":" ; ";" ; "<" etc. ).
Which made me to take a other way. In the time my teacher gave me some advices, and i made a code.
Quote:
public class BigInt{
char[] tab;
}
Quote:
public BigInt(String a) {
tab = toCharArray();
return;
}
Quote:
public BigInt add(BigInt number) {
String a = number.toString();
int memory= 0;
char[] tabAdd= a.toCharArray();
String RESULT= "";
int result;
for (int i = tablica.length - 1; i >= 0; i--) {
result= tab[i] - '0' + tabAdd[i] - '0' + memory;
if (memory > 9) {
reuslt= result - 10;
memory = 1;
} else
memory = 0;
RESULT= result + result;
}
if (pamiec == 1)
WYNIK ="11"+WYNIK;
return new DuzaLiczba(WYNIK);
And on the main class :
Quote:
public class Main {
public static void main(String[] args) {
BigInt x = new BigInt("33333333");
System.out.println(x);
BigInt result = x.add(new BigInt("33333333"));
System.out.println(wynik);
}
}
And the result of that is :
If the result is greater than 10 in any charArraySegment it works also good :
Quote:
BigInt x = new BigInt("33333333");
System.out.println(x);
BigInt result = x.add(new BigInt("33333333"));
System.out.println(wynik);
Result : Quote:
33333333
111111110
BUT :D it starts to break when x have different lenght than result. My teacher gave me some thoughts, but i really do not know what i have to do now.
Can you help me in?
Make it work with different lengths of arrays.
And write a subtraction method? I made a method by copying a add method and just change :
Quote:
wynik = tablica[i] - '0' + tablicaDodawania[i] - '0' + pamiec;
to :
Quote:
wynik = tablica[i] - '0' - tablicaDodawania[i] - '0' + pamiec;
But it was for sure bad idea :).
Thanks for the thoughts. If you have any questions, ask here, i will track this thread.