public class Solution {
public String multiply(String num1, String num2) {
int len1 = num1.length(), len2 = num2.length();
int[] num3 = new int[len1 + len2];
int i, j, product, carrier;
for (i = len1 - 1; i >= 0; i--) {
carrier = 0;
for (j = len2 - 1; j >= 0; j--) {
product = carrier + num3[i + j + 1] + Character.getNumericValue(num1.charAt(i)) * Character.getNumericValue(num2.charAt(j));
num3[i + j + 1] = product % 10;
carrier = product / 10;
}
num3[i + j + 1] = carrier;
}
StringBuilder sb = new StringBuilder();
i = 0;
while (i < num3.length - 1 && num3[i] == 0) {
i++;
}
while (i < num3.length) {
sb.append(num3[i]);
i++;
}
return sb.toString();
}
}
给一个数组,都是整型,比如[1, 2, 3]。取每个数乘以2, 输出结果数组。有点类似string mulplication。比如 [5, 5, 5] 输出 [1, 1, 1, 0]. Follow up: 如果不reverse结果数组,要怎么做。回答用queue。
/**
* Created by yang on 1/3/17.
*/
public class Solution6 {
public static int[] multiplyArray(int[] nums) {
if (nums == null || nums.length == 0) {
return null;
}
int[] rst = new int[nums.length];
int digit = 0, carrier = 0;
for (int i = nums.length - 1; i >= 0; i--) {
int product = 2 * nums[i];
digit = carrier + product % 10;
carrier = product / 10;
rst[i] = digit;
}
if (carrier == 0) return rst;
int[] newArr = new int[nums.length + 1];
for (int i = newArr.length - 1; i >= 0; i--) {
if (i == 0) {
newArr[0] = carrier;
} else {
newArr[i] = rst[i - 1];
}
}
return newArr;
}
public static void main(String[] args) {
int[] nums = new int[]{6, 9, 3};
int[] rst = multiplyArray(nums);
for (int i : rst) {
System.out.print(i + " ");
}
}
}