LeetCode - Easy - 415. Add Strings

Topic

  • String

Description

https://leetcode.com/problems/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.

Analysis

方法一:按照整数加法普通思路相加即可。

方法二:在方法一的基础上进行修改。

Submission

public class AddStrings {
    
    
	//方法一:最初版
	public String addStrings1(String num1, String num2) {
    
    
		int index1 = num1.length() - 1, index2 = num2.length() - 1;
		StringBuilder sb = new StringBuilder();

		int carry = 0;
		while (index1 >= 0 || index2 >= 0) {
    
    
			int a = index1 >= 0 ? num1.charAt(index1--) - '0' : 0;
			int b = index2 >= 0 ? num2.charAt(index2--) - '0' : 0;
			int s = a + b + carry;

			carry = s >= 10 ? 1 : 0;
			int rs = s >= 10 ? s - 10 : s;
			sb.insert(0, rs);
		}

		if (carry > 0)
			sb.insert(0, carry);

		return sb.toString();
	}

	//方法二:方法一的改进版
	public String addStrings2(String num1, String num2) {
    
    
		int index1 = num1.length() - 1, index2 = num2.length() - 1;
		StringBuilder sb = new StringBuilder();

		int carry = 0;
		while (index1 >= 0 || index2 >= 0 || carry == 1) {
    
    
			int a = index1 >= 0 ? num1.charAt(index1--) - '0' : 0;
			int b = index2 >= 0 ? num2.charAt(index2--) - '0' : 0;
			int s = a + b + carry;

			carry = s >= 10 ? 1 : 0;
			int rs = s >= 10 ? s - 10 : s;
			sb.append(rs);
		}

		return sb.reverse().toString();
	}
}

Test

import static org.junit.Assert.*;
import org.junit.Test;

public class AddStringsTest {
    
    

	@Test
	public void test() {
    
    
		AddStrings obj = new AddStrings();

		for (int a = 0; a < 1000; a++)
			for (int b = 0; b < 1000; b++) {
    
    
				assertEquals(String.valueOf(a + b), obj.addStrings1(String.valueOf(a), String.valueOf(b)));
				assertEquals(String.valueOf(a + b), obj.addStrings2(String.valueOf(a), String.valueOf(b)));
			}
	}
}

猜你喜欢

转载自blog.csdn.net/u011863024/article/details/114345091