大整数的运算基本就是对数组进行加减乘除。
题目一: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.
思路:用vector存数组,而且高位存在数组的地位。小心最高位进位就可以了。
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int n=digits.size();
vector<int> res;
if(n==0) return res;
int sum=1;
for(int i=n-1;i>=0;i--){
sum+=digits[i];
digits[i]=sum%10;
sum/=10;
}
if(sum>0) res.push_back(sum);
for(int i=0;i<n;i++)
res.push_back(digits[i]);
return res;
}
};
题目二: Add Binary
Given two binary strings, return their sum (also a binary string). For example, a="11", b="1", Return "100".
思路:这道题也没什么难度。需要注意的是,最高位最在字符串最低位。而且同样就不进位的问题。
class Solution {
public:
string addBinary(string a, string b) {
string res="";
int carry=0, val;
int i=0;
while(i<a.length() || i<b.length()){
int sum=carry;
if(i<a.length()) sum=sum+a[a.length()-1-i]-'0'; //最低位在字符串的最右边
if(i<b.length()) sum=sum+b[b.length()-1-i]-'0';
val=sum%2;
carry=sum/2;
res=char(val+'0')+res;
i++;
}
if(carry) res=char(carry+'0')+res;
return res;
}
};
题目三: Multiply String
Given two numbers represented as strings, return multiplication of the numbers as a string. Note: The number can be arbitrarily large and arenon-negative.
class Solution {
public:
string add(string a, string b){ //两个字符串相加
if(a.length()==0) return b;
if(b.length()==0) return a;
string res="";
int i=0;
int sum;
int carry=0;
while(i<a.length() || i<b.length()){
sum=carry;
if(i<a.length()) sum=sum+a[a.length()-1-i]-'0';
if(i<b.length()) sum=sum+b[b.length()-1-i]-'0';
int val=sum%10;
res=char(val+'0')+res;
carry=sum/10;
i++;
}
if(carry) res=char(carry+'0')+res;
return res;
}
string multiply(string s, char c){ //一个字符和一个字符串相乘
string res="";
int sum=0;
int carry=0;
int i=s.length()-1;
while(i>=0){
sum=carry;
sum=sum+(c-'0')*(s[i]-'0');
int val=sum%10;
carry=sum/10;
res=char('0'+val)+res;
i--;
}
if(carry) res=char('0'+carry)+res;
return res;
}
string multiply(string num1, string num2) {
if(num2=="0" || num1=="0") return "0";
string s3="", s="";
for(int i=0;i<num2.length();i++){
string s(i,'0');
s=multiply(num1, num2[num2.length()-1-i])+s;
s3=add(s3,s);
}
return s3;
}
};
题目四: Divide Two Integers
Divide two integers without using multiplication, division and mod operator.
思路:乘法的本质数相加,而除法的本质是相减。最直接的方法是循环的做减法,但是会TLE。一种解救方法就是采用二分的方法。此外,还需考虑除数符号、溢出等问题。
class Solution {
public:
int divide(int dividend, int divisor) {
long long a=abs((double)dividend); //先将int转成double
long long b=abs((double)divisor); //这里如果不加long long或者加double,就会当是INT_MIN的时候溢出
long long res=0;
while(a>=b){
long long start=b;
for(int cnt=0; start<=a; cnt++, start=start*2){
a=a-start;
res+=(1<<cnt); //右移操作的优先级比较低!
}
}
return ((dividend^divisor)>>31) ? (-res) : (res); //取双方的符号位!
}
};