zoukankan      html  css  js  c++  java
  • 大数相加算法

    @Test
    public void testBig() {
    System.out.println(bigAdd("123456789", "9999999999999999999999999"));
    }

    public static String bigAdd(String a, String b) {
    char[] charsA = new StringBuilder(a).reverse().toString().toCharArray();
    char[] charsB = new StringBuilder(b).reverse().toString().toCharArray();

    int maxLength = Math.max(charsA.length, charsB.length);

    int[] result = new int[maxLength + 1];

    int temp = 0;
    for (int i = 0; i <= maxLength; i++) {
    temp = result[i];

    if (i < charsA.length) {
    temp += charsA[i] - '0';
    }

    if (i < charsB.length) {
    temp += charsB[i] - '0';
    }

    if (temp >= 10) {
    temp -= 10;
    result[i + 1] = 1;
    }

    result[i] = temp;

    }

    StringBuilder sb = new StringBuilder();
    boolean flag = true;

    for (int i = maxLength; i >= 0; i--) {
    if (result[i] == 0 && flag) {
    continue;
    }

    flag = false;
    sb.append(result[i]);
    }

    return sb.toString();

    }
    ---------------------
    作者:懒惰的毛毛虫
    来源:CSDN
    原文:https://blog.csdn.net/u013278314/article/details/85171400
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    [NOIP2008] 传纸条
    [NOIP2006] 能量项链
    [poj2393] Yogurt factory
    [poj3069] Saruman's Army
    [NOIP2011] 观光公交
    [NOIP2010] 关押罪犯
    [洛谷2744] 量取牛奶
    [poj3281] Dining
    关于几类STL容器的swap复杂度问题
    折半法
  • 原文地址:https://www.cnblogs.com/ning123/p/10919605.html
Copyright © 2011-2022 走看看