Created
February 12, 2019 23:37
-
-
Save derjust/31e0c0ca79caca2b134688965bc965ed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package patty; | |
import java.util.Iterator; | |
import java.util.Vector; | |
public class HugeInteger { | |
private boolean sign; | |
//TODO Vector is a super-outdated class.. | |
private Vector<Integer> vector; | |
private HugeInteger(boolean sign, Vector<Integer> vector) { | |
this.sign = sign; | |
this.vector = new Vector<Integer>(vector.size()); | |
for(int i = vector.size() -1 ; i >= 0 ; i--) | |
{ | |
this.vector.add(vector.get(i)); | |
} | |
} | |
public String toString() { | |
StringBuilder sb = new StringBuilder(); | |
if (sign) { | |
sb.append("+"); | |
} else { | |
sb.append("-"); | |
} | |
Iterator<Integer> it = vector.iterator(); | |
while(it.hasNext()) { | |
sb.append(it.next()); | |
} | |
return sb.toString(); | |
} | |
public static HugeInteger parse(String s) { | |
if (s == null) { | |
throw new IllegalArgumentException("s must not be null!"); | |
} | |
boolean sign; | |
int startPos; | |
if ('-' == s.charAt(0)) { | |
startPos = 1; | |
sign = false; | |
} else if ('+' == s.charAt(0)) { | |
startPos = 1; | |
sign = true; | |
} else { | |
startPos = 0; | |
sign = true; | |
} | |
Vector<Integer> vector = new Vector<>(); | |
for (int pos=startPos; pos < s.length(); pos++) { | |
// based on the description i think the prof wants this fu - actually this is dangerous for any non-ASCII input! | |
int digit = s.charAt(pos) - '0'; | |
vector.add(digit); | |
} | |
return new HugeInteger(sign, vector); | |
} | |
public HugeInteger addition(HugeInteger summand2) { | |
Vector<Integer> result = new Vector<Integer>(); | |
int carryover = 0; | |
int i; | |
for(i=0; i < Math.max(this.vector.size(), summand2.vector.size()); i++) { | |
int sum1; | |
if (this.vector.size()<i) { | |
sum1 = 0; | |
} else { | |
sum1 = this.vector.get(i); | |
} | |
int sum2; | |
if (summand2.vector.size()<i) { | |
sum2 = 0; | |
} else { | |
sum2 = summand2.vector.get(i); | |
} | |
int sum = carryover + sum1 + sum2; | |
carryover = sum / 10; | |
result.add(sum % 10); | |
} | |
return new HugeInteger(this.sign, result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment