大数相加,相减,相乘算法(JAVA代码)

415. Add Strings(大数相加)

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

思想:

从后往前相加。设置个进位的变量。这里c++用到了revervse()函数

C++ AC代码:

Space O(1) Time O(n)

class Solution {
public:
    string addStrings(string num1, string num2) {
	int len1 = num1.size()-1;
        int len2 = num2.size()-1;
        int carry = 0;
        string res ="";
        while(len1>=0||len2>=0||carry){
            int sum = 0;
            if(len1>=0) sum +=num1[len1--]-'0';
            if(len2>=0) sum +=num2[len2--]-'0';
            sum+=carry;
            carry = sum/10;
            sum %=10;
            res = res + to_string(sum);
        }
        reverse(res.begin(),res.end());  //注意要反转一次 
        return res;
    }
};

JAVA AC代码:

Space O(n) Time O(n)

public class Solution {
    public String addStrings(String num1, String num2) {
            int len1 = num1.length()-1;
			int len2 = num2.length()-1;
			int carry = 0;
			int k = Math.max(len1, len2);
			int sum[] = new int[k+1];
			while(len1>=0||len2>=0){
				int temp1 = len1>=0?(num1.charAt(len1)-'0'):0;
				int temp2 = len2>=0?(num2.charAt(len2)-'0'):0;
				int temp = temp1+temp2+carry;
				sum[k] =temp%10;
				carry = temp/10;
				k--;
				len1--;
				len2--;
			}
			StringBuilder s = new StringBuilder();
		    if(carry!=0) s.append(carry);
		    for(int digit:sum){
		    	s.append(digit);
		    }
        return s.toString();
    }
}

大数相减

思想:

先要注意判断,大数减小数正常相减,小数减大数相当于大数减小数前添加个负号
也是从后向前相减,个位开始相减,相减时先加个10,结果模上10就是当前位的值了。判断是否需要从高位借值,相减加10的结果除以10大于1的话就可以判断没有从高位借了值了( 模10和除以10 这是个小技巧

JAVA 代码:

Space O(n) Time O(n) 因为leetcode 貌似没有找到大数相减的题 所以在IDE上写的 可以直接运行

public class testString {

	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			String s1 = sc.next();
			String s2 = sc.next();
			//  大数串s1 - s2
			int len1 = s1.length();
			int len2 = s2.length();
			if(len1>len2)   //s1长度大于s2 正常相减
				System.out.println(subStract(s1, s2));
			else if(len1<len2){//s1长度小于s2 反向相减 加负号
				System.out.println("-"+subStract(s2, s1));
			}else{ //s1长度等于s2 比较s1和s2值谁大 
				int compare = s1.compareTo(s2);
				if(compare==0) System.out.println(0);
				else if(compare>0)
					System.out.println(subStract(s1, s2));
				else
					System.out.println("-"+subStract(s2, s1));
					
			}
				
		}
	}
	public static String subStract(String num1,String num2){
		int len1 = num1.length()-1;
		int len2 = num2.length()-1;
		int max = len1>len2?len1:len2;
		int brower = 0;
		int res[] = new int[max+1];
		int k = max;
		while(len1>=0 ||len2>=0){
			int div=10; 
			div += len1>=0?num1.charAt(len1)-'0':0;
			div -= len2>=0?num2.charAt(len2)-'0':0;
			div -=brower;
			res[k--] = div%10;
			brower = div/10==0?1:0;
			len2--;
			len1--;
		}
		int i=0;
		if(res[i]==0)
			i++;
		StringBuilder s = new StringBuilder();
		for(int j=i;j<=max;j++){
			
			s.append(res[j]);
		}
		return s.toString();
	}
}

43. Multiply Strings(大数相乘)

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

思想:

这题的技巧在于复用同一个结果数组存放上次的计算结果。因为被乘数每一位数字和乘数相乘的结果是依次错开的

JAVA AC代码:

public class Solution {
    public String multiply(String num1, String num2) {
            int len1 = num1.length();
			int len2 = num2.length();
			int k = len1+len2,i,j;
			int sum[] = new int[k]; //乘积的结果最多是两个位数之和
			for( i=len1-1;i>=0;i--){
				int carry = 0; //进位数值
				for( j=len2-1;j>=0;j--){
					int temp1 = num1.charAt(i)-'0';
					int temp2 = num2.charAt(j)-'0';
                    ///每一位的乘积等于 之前这一位的结果加上进位的值,加上两数相乘结果
					int temp = temp1*temp2+carry+sum[i+j+1];
					sum[i+j+1] =temp%10;
					carry = temp/10;
				}
				sum[i+j+1] = carry;
			}
			StringBuilder s = new StringBuilder();
  去掉前面无用的0
			i=0;
			while(i<k-1&&sum[i]==0) i++;
		    for(;i<k;i++){
		    	s.append(sum[i]);
		    }
        return s.toString();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值