❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

415. Add Strings

LeetCode number 415, String.

This problem is like add binary number in String.

Description:

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

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

Input / Ouput :

Example 1:

Input: num1 = "11", num2 = "123"
Output: "134"

Example 2:

Input: num1 = "456", num2 = "77"
Output: "533"

Example 3:

Input: num1 = "0", num2 = "0"
Output: "0"

Algorithm:

  1. Add numbers from end to start so, initials i =num1.length() -1 and j=num2.length()-1.
  2. Intialize the carry =0 as the remaining number.
  3. use Stringbuffer for the mutable property in string.
  4. Now Add the continuously,
    • carry += num1.charAt(i) and i– upto i>=0.
    • carry += num2.charAt(j) and j– upto j>=0.
    • stringBuffer. append(carry%10).
    • carry /= 10.
  5. then reverse the stringBuffer by st.reverse().

code :

  int i=num1.length()-1, j=num2.length()-1, carry=0;
        StringBuffer sb = new StringBuffer();
        while(i>=0 || j>=0 || carry > 0)
        {
        	// condtion for string out of boundary i.e means i should less then 0
        	if(i>=0)
        		carry += num1.charAt(i--) - '0';
        	
        	if(j>=0)
        		carry += num2.charAt(j--) - '0';
        	sb.append(carry%10);
        	carry /= 10;
        }
        
		return sb.reverse().toString();

Reference :

https://leetcode.com/problems/add-strings

❌
❌