Leetcode中的大整数

大整数的运算基本就是对数组进行加减乘除。


题目一: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 plusOne(vector &digits) {
        int n=digits.size();
        vector 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

题目二: 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

题目三: 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=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

题目四: 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<>31) ? (-res) : (res);  //取双方的符号位!
    } 
};



你可能感兴趣的:(Leetcode)