用連結串列的方式實現大數相減-Java實現

Miaoji is a Cat發表於2020-12-04

package com.company;

import java.util.Objects;

public class Main {

  public static void main(String[] args) {
    // write your code here
    String num1 = "30000001";
    String num2 = "1000003";
    if (!isDigitalNum(num1) || !isDigitalNum(num2)) {
      System.out.println("數值不合法");
      return;
    }

    Node node1 = new Node.Builder().setNumber(num1).build();
    Node node2 = new Node.Builder().setNumber(num2).build();
    String result = node1.next.add(node2.next, 0);
    for (int i = 0; i < result.length(); ++i) {
      if (result.charAt(i) != '0') {
        System.out.println(result.substring(i));
        break;
      }
    }
  }

  private static boolean isDigitalNum(String num) {
    if (Objects.isNull(num) || "".equals(num))
      return false;
    for (int i = 0; i < num.length(); i++) {
      if (num.charAt(i) < '0' && num.charAt(i) > '9') {
        return false;
      }
    }
    return true;
  }


  public static class Node {
    int value;
    Node next;

    private void initCharacterChain(String num1) {
      for (int i = num1.length() - 1; i >= 0; --i) {
        this.value = num1.charAt(i);
        this.next = new Node();
      }
    }

    public static class Builder {
      String numb;

      public Builder setNumber(String numb) {
        this.numb = numb;
        return this;
      }

      public Node build() {

        Node root = new Node();
        Node p = root;
        for (int i = numb.length() - 1; i >= 0; --i) {
          Node node = new Node();
          node.value = numb.charAt(i) - '0';
          p.next = node;
          p = p.next;
        }
        return root;
      }
    }

    public String add(Node node, int carrier) {
      if (this.next == null && node.next == null) {
        int sum = this.value + node.value + carrier;
        return sum + "";
      }
      int sum = 0;
      if (node == null) {
        node = new Node();
      }
      if (node.next == null) {
        node.next = new Node();
      }
      if (this.next == null) {
        this.next = new Node();
      }
      sum = node.value + carrier + this.value;
      return this.next.add(node.next, sum / 10) + "" + sum % 10;
    }
  }

}

 

相關文章