2015年11月14日星期六

BigInt add

刚刚面完第二轮电面,原题 BigInt, 不过把详细一点的放在这里,和我的答案。// This is the text editor interface. 
// Anything you type or change here will be seen by the other person in real time.
. more info on 1point3acres.com
/*
* class BigInt, to represent non-negative integers of arbitrary size
        * constructor accept a String, representing this non-neg int (e.g. "50"), assume valid input    . visit 1point3acres.com for more.
        * needs to be able to add to another BigInt, and return their sum as a new BigInt object
        * immutable
            * new BigInt("20").add(new BigInt("30")) --> BigInt("50")

import java.util.Random;

public class Solution {

public String add(String str1, String str2) {
StringBuilder sb = new StringBuilder();
int i1 = str1.length() - 1;
int i2 = str2.length() - 1;
int carry = 0;
int base = 10;
while (i1 >= 0 || i2 >= 0 || carry != 0) {
int val = carry;
val += i1 >= 0 ? (str1.charAt(i1) - '0') : 0;
val += i2 >= 0 ? (str2.charAt(i2) - '0') : 0;
carry = val / base;
sb.append(val % base);
i1--;
i2--;
}
return sb.reverse().toString();
}

public static void main(String args[]) {
Solution s = new Solution();
Random r = new Random();
int n1 = r.nextInt(100000000);
int n2 = r.nextInt(100000000);
String n3 = s.add(Integer.toString(n1), Integer.toString(n2));
System.out.println((n1 + n2) == Integer.parseInt(n3));
}

}

没有评论:

发表评论