Subtraction of Two Strings

package strings;

import java.util.ArrayList;
import java.util.Collections;

class Subtract {
    static Integer carry = 0;

    public static void main(String args[]) {
        // String s1 = "7654729850328997631007285998163550104";
        // String s2 = "5980139243970186632651869926335829102";

        String s1 = "1321";
        String s2 = "0254";

        subtract(s1, s2);
    }

    public static void subtract(String a, String b) {
        ArrayList<String> res = new ArrayList<String>();
        int i = a.length() - 1;
        int j = b.length() - 1;
        int diff = 0;
        while (true) {
            int i1 = Integer.parseInt(Character.toString(a.charAt(i)));
            int i2 = Integer.parseInt(Character.toString(b.charAt(j)));
            i1 = i1 - diff;
            if (i1 - i2 < 0) {
                i1 = i1 + 10;
                diff = 1;
            } else {
                diff = 0;
            }
            int i3 = i1 - i2;
            res.add(i3 + "");
            i--;
            j--;
            if (i < 0) {
                // res.add(carry.toString());
                break;
            }
        }
        Collections.reverse(res);
        for (String r : res) {
            System.out.print(r);
        }
    }

}

Comments

Popular posts from this blog

Java important topics list for interviews

Tough Sql practise questions for interviews involving SELECT queries - Part 2

DBMS important topics list for interviews

Program to find number lines and words in a given file

Tough Sql practise questions for interviews involving SELECT queries - Part 1

Producer Consumer Problem with Blocking Queue in Java.

Animation for String search - KMP Algorithm

Interactive Data Structure visualizations/animations for algorithms

Replace Occurances of the given string