https://leetcode.com/problems/multiply-strings/
http://gongxuns.blogspot.com/2013/01/leetcode-multiply-strings.html
class BigInt {
BigInt(int capacity) {
sign = 1;
digits = new char[capacity];
}
BigInt(String s) {
sign = s.charAt(0) == '-' ? -1 : 1;
digits = new char[s.length() - (s.charAt(0) == '-' ? 1 : 0)];
for (int i = s.length() - 1, j = 0; i >= (s.charAt(0) == '-' ? 1 : 0); --i, ++j) {
if (Character.isDigit(s.charAt(i))) {
digits[j] = (char) (s.charAt(i) - '0');
}
}
}
BigInt multiply(BigInt n) {
BigInt result = new BigInt(digits.length + n.digits.length);
result.sign = sign * n.sign;
int i = 0, j = 0;
for (i = 0; i < n.digits.length; ++i) {
if (n.digits[i] != 0) {
int carry = 0;
for (j = 0; j < digits.length || carry > 0; ++j) {
int nDigit = result.digits[i + j]
+ (j < digits.length ? n.digits[i] * digits[j] : 0)
+ carry;
result.digits[i + j] = (char) (nDigit % 10);
carry = nDigit / 10;
}
}
}
// If one number is 0, the result size should be 0.
if ((digits.length == 1 && digits[0] == 0)
|| (n.digits.length == 1 && n.digits[0] == 0)) {
result.sign = 1;
result.digits = Arrays.copyOf(result.digits, 1);
} else {
result.digits = Arrays.copyOf(result.digits, i + j - 1);
}
return result;
}
}
http://www.1point3acres.com/bbs/thread-148690-1-1.html
第二题: square a very long number. For an example, the number 12 is represented in array as [2,1], 12^2 = 144, the output should be [4,4,1]
airbnb面试题汇总
Given two non-negative integers
num1
and num2
represented as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
Start from right to left, perform multiplication on every pair of digits, and add them together. Let's draw the process! From the following draft, we can immediately conclude:
`num1[i] * num2[j]` will be placed at indices `[i + j`, `i + j + 1]`
public String multiply(String num1, String num2) {
int m = num1.length(), n = num2.length();
int[] pos = new int[m + n];
for(int i = m - 1; i >= 0; i--) {
for(int j = n - 1; j >= 0; j--) {
int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
int p1 = i + j, p2 = i + j + 1;
int sum = mul + pos[p2];
pos[p1] += sum / 10;
pos[p2] = (sum) % 10;
}
}
StringBuilder sb = new StringBuilder();
for(int p : pos) if(!(sb.length() == 0 && p == 0)) sb.append(p);
return sb.length() == 0 ? "0" : sb.toString();
}
This is the standard manual multiplication algorithm. We use two nested for loops, working backward from the end of each input number. We pre-allocate our result and accumulate our partial result in there. One special case to note is when our carry requires us to write to our sum string outside of our for loop.
At the end, we trim any leading zeros, or return 0 if we computed nothing but zeros.
string multiply(string num1, string num2) {
string sum(num1.size() + num2.size(), '0');
for (int i = num1.size() - 1; 0 <= i; --i) {
int carry = 0;
for (int j = num2.size() - 1; 0 <= j; --j) {
int tmp = (sum[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;
sum[i + j + 1] = tmp % 10 + '0';
carry = tmp / 10;
}
sum[i] += carry;
}
size_t startpos = sum.find_first_not_of("0");
if (string::npos != startpos) {
return sum.substr(startpos);
}
return "0";
}
[leetcode] Multiply Strings | 大整数的字符串乘法- 直接乘会溢出,所以每次都要两个single digit相乘,最大81,不会溢出。
- 比如385 * 97, 就是个位=5 * 7,十位=8 * 7 + 5 * 9 ,百位=3 * 7 + 8 * 9 …
可以每一位用一个Int表示,存在一个int[]里面。 - 这个数组最大长度是num1.len + num2.len,比如99 * 99,最大不会超过10000,所以4位就够了。
- 这种个位在后面的,不好做(10的0次方,可惜对应位的数组index不是0而是n-1),
所以干脆先把string reverse了代码就清晰好多。 - 最后结果前面的0要清掉。
public String multiply(String num1, String num2) { num1 = new StringBuilder(num1).reverse().toString(); num2 = new StringBuilder(num2).reverse().toString(); // even 99 * 99 is < 10000, so maximaly 4 digits int[] d = new int[num1.length() + num2.length()]; for (int i = 0; i < num1.length(); i++) { int a = num1.charAt(i) - '0'; for (int j = 0; j < num2.length(); j++) { int b = num2.charAt(j) - '0'; d[i + j] += a * b; } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < d.length; i++) { int digit = d[i] % 10; int carry = d[i] / 10; sb.insert(0, digit); if (i < d.length - 1) d[i + 1] += carry; } //trim starting zeros while (sb.length() > 0 && sb.charAt(0) == '0') { sb.deleteCharAt(0); } return sb.length() == 0 ? "0" : sb.toString(); }
public String multiply(String num1, String num2) {
if (num1 == null || num1.length() == 0 ||
num2 == null || num2.length() == 0)
return "";
if (num1.equals("0") || num2.equals("0")) // Either one is 0
return "0";
int m = num1.length(), n = num2.length();
// Multiply single digit of each number and add up products at each position
int[] prods = new int[m+n];
for (int i = n-1; i >= 0; i--)
for (int j = m-1; j >= 0; j--)
prods[i+j+1] += (num2.charAt(i)-'0') * (num1.charAt(j)-'0');
// Keep a single digit at each position and add carry to a higher position
StringBuilder result = new StringBuilder();
for (int i = n+m-1; i >= 0; i--) {
result.insert(0, prods[i]%10);
if (i > 0)
prods[i-1] += prods[i] / 10; // Carry
}
// Get rid of one leaing "0" (if any)
if (result.charAt(0) == '0')
result.deleteCharAt(0);
return result.toString();
}
http://rleetcode.blogspot.com/2014/01/multiply-strings-java.htmlhttp://gongxuns.blogspot.com/2013/01/leetcode-multiply-strings.html
public String multiply(String num1, String num2) { int[] num = new int[num1.length()+num2.length()]; for(int i=0;i<num1.length();i++){ int carry = 0; int a = num1.charAt(num1.length()-1-i)-'0'; for(int j=0;j<num2.length();j++){ int b = num2.charAt(num2.length()-1-j)-'0'; num[i+j]+=carry+a*b; carry=num[i+j]/10; num[i+j]%=10; } num[i+num2.length()]+=carry; } int i=num.length-1; while(i>0 && num[i]==0) i--; StringBuilder temp = new StringBuilder(""); while(i>=0) temp.append((char)('0'+num[i--])); return temp.toString(); }http://www.jiuzhang.com/solutions/multiply-strings/
public String multiply(String num1, String num2) { if (num1 == null || num2 == null) { return null; } int len1 = num1.length(), len2 = num2.length(); int len3 = len1 + len2; int i, j, product, carry; int[] num3 = new int[len3]; for (i = len1 - 1; i >= 0; i--) { carry = 0; for (j = len2 - 1; j >= 0; j--) { product = carry + num3[i + j + 1] + Character.getNumericValue(num1.charAt(i)) * Character.getNumericValue(num2.charAt(j)); num3[i + j + 1] = product % 10; carry = product / 10; } num3[i + j + 1] = carry; } StringBuilder sb = new StringBuilder(); i = 0; while (i < len3 - 1 && num3[i] == 0) { i++; } while (i < len3) { sb.append(num3[i++]); } return sb.toString(); }From EPI
class BigInt {
BigInt(int capacity) {
sign = 1;
digits = new char[capacity];
}
BigInt(String s) {
sign = s.charAt(0) == '-' ? -1 : 1;
digits = new char[s.length() - (s.charAt(0) == '-' ? 1 : 0)];
for (int i = s.length() - 1, j = 0; i >= (s.charAt(0) == '-' ? 1 : 0); --i, ++j) {
if (Character.isDigit(s.charAt(i))) {
digits[j] = (char) (s.charAt(i) - '0');
}
}
}
BigInt multiply(BigInt n) {
BigInt result = new BigInt(digits.length + n.digits.length);
result.sign = sign * n.sign;
int i = 0, j = 0;
for (i = 0; i < n.digits.length; ++i) {
if (n.digits[i] != 0) {
int carry = 0;
for (j = 0; j < digits.length || carry > 0; ++j) {
int nDigit = result.digits[i + j]
+ (j < digits.length ? n.digits[i] * digits[j] : 0)
+ carry;
result.digits[i + j] = (char) (nDigit % 10);
carry = nDigit / 10;
}
}
}
// If one number is 0, the result size should be 0.
if ((digits.length == 1 && digits[0] == 0)
|| (n.digits.length == 1 && n.digits[0] == 0)) {
result.sign = 1;
result.digits = Arrays.copyOf(result.digits, 1);
} else {
result.digits = Arrays.copyOf(result.digits, i + j - 1);
}
return result;
}
}
http://www.1point3acres.com/bbs/thread-148690-1-1.html
第二题: square a very long number. For an example, the number 12 is represented in array as [2,1], 12^2 = 144, the output should be [4,4,1]
airbnb面试题汇总
但是string里面的数可以为负typedef vector<int> bigInt;
bigInt make_bigInt(string num) {
bigInt tmp;
transform(num.rbegin(), num.rend(), back_inserter(tmp), [](char c) { return c - '0';});
return tmp;
}
string make_string(bigInt num) {
string tmp;
transform(find_if(num.rbegin(), prev(num.rend()), [](int c){ return c != 0;}), num.rend(),
back_inserter(tmp), [](int c) { return c + '0';});
return tmp;
}
bigInt multiply(bigInt const& n1, bigInt const& n2) {
bigInt n(n1.size() + n2.size());
for (int i = 0; i < n1.size(); ++i)
for (int j = 0; j < n2.size(); ++j) {
n[i + j] += n1[i] * n2[j];
n[i + j + 1] += n[i + j] / 10;
n[i + j] %= 10;
}
return n;
}
string multiply(string num1, string num2) {
if(num1.empty() || num2.empty()) return "0";
bool sign = true;
if (num1[0] == '-' || num1[0] == '+') {
if (num1[0] == '-') sign = !sign;
num1.sustr(1);
}
if (num2[0] == '-' || num2[0] == '+') {
if (num2[0] == '-') sign = !sign;
num2.sustr(1);
}
string ans = make_string(multiply(make_bigInt(num1), make_bigInt(num2)));
if (ans == "0") return ans;
return (sign ? "" : "-") + ans;
}
Read full article from LeetCode - Multiply Strings | Darren's Blog