一. Plus One
题目:Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
大意:一个非负正数用数组A表示,例如【1,9,9】表示199,题目要求A+1后返回数组B。
解析:要分成两种情况,最高位不进位、最高位进位。设置一个变量表示进位carry,从右向左扫描数组加carry,当进位为0的时候,可以结束扫描。
若扫描完最高位,carry依旧是1,那么需要建立一个新的数组。
public class Solution {
public int[] plusOne(int[] d) {
if(d==null) return null;
if(d.length==0) return new int[] {1};
int carry=1;//初始化为1,因为个位要加1
for(int i=d.length-1; i>=0; i--){
d[i]+=carry;
carry=d[i]/10;
d[i]=d[i]%10;
if(carry==0) return d;//如果进位为0,那么就可以直接返回数组d
}
d[0]=d[0]%10;
int[]res=new int[d.length+1];
for(int i=0;i<d.length;i++)
res[i+1]=d[i];
res[0]=1;
return res;
}
}
二. Multiply Strings(大数相乘)
两个题目类似
题目:Given two numbers represented as strings, return multiplication of the numbers as a string.
Note:
- The numbers can be arbitrarily large and are non-negative.
- Converting the input string to integer is NOT allowed.
- You should NOT use internal library such as BigInteger.
解析:大数相乘,模拟手写的思想。假设两个数A*B=C,那么C的第k位,C[k]=A[0]*B[k]+A[1]*B[k-1]+……A的第i位+B的第j位=k。
//大数相乘的题目,类似于两个数组相加的题目
public class Solution {
public static String multiply(String num1, String num2) {
if(num1==null || num2==null)
return null;
int len1=num1.length();
int len2=num2.length();
int len=len1+len2;//返回结果的长度<=两个数长度的和
int[]res=new int[len];
for(int k=0;k<len;k++){//计算相乘后未进位的结果
for(int i=0;i<=k;i++){
int a=i<len1?num1.charAt(len1-i-1)-'0':0;
int b=(k-i)<len2?num2.charAt(len2-k+i-1)-'0':0;
res[k]+=a*b;
}
}
int carry=0;
for(int i=0;i<len;i++){//进位
int temp=res[i]+carry;
res[i]=temp%10;
carry=temp/10;
}
return arrayToString(res);
}
/**
* int数组颠倒顺序转化为字符串,同时去掉先导零
*/
public static String arrayToString(int[]a){
StringBuilder sb=new StringBuilder();
boolean flag=true;//尚未遇到非零数字
for(int i=a.length-1;i>=0;i--){
if(a[i] !=0) flag=false;
if(!flag || a[i] !=0 || i==0) sb.append(a[i]);
}
return sb.toString();
}
}