zoukankan      html  css  js  c++  java
  • 超长正数相加

    输入两个字符串数字,输出相加后的结果,string型

    思路:

    定义个两个数字的数组,然后将每一个数据加入

    两个数组进行相加,将结果保存到result数组中即可

    private static void AddLongInteger(String one,String two) {
    int oneLen = one.length();
    int twoLen = two.length();
    int[] oneArr = new int[oneLen];
    int[] twoArr = new int[twoLen];
    int[] result = new int[oneLen > twoLen ? oneLen + 1 : twoLen + 1];
    char[] oneChars = one.toCharArray();
    char[] twoChars = two.toCharArray();
    for (int i = 0; i < oneChars.length; i++) {
    oneArr[i] = oneChars[i] - '0';
    }
    for (int i = 0; i < twoChars.length; i++) {
    twoArr[i] = twoChars[i] - '0';
    }
    int oneIndex = oneArr.length - 1;
    int twoIndex = twoArr.length - 1;
    int index = result.length - 1;
    while (oneIndex >=0 && twoIndex >= 0){
    result[index] += oneArr[oneIndex] + twoArr[twoIndex];
    if(result[index] > 9){
    result[index] = result[index] % 10;
    result[index-1] = 1;
    }
    oneIndex--;
    twoIndex--;
    index--;
    }

    while (oneIndex >=0){
    result[index] += oneArr[oneIndex];
    if(result[index] > 9){
    result[index] = result[index] % 10;
    result[index-1] = 1;
    }
    index--;
    oneIndex--;
    }
    while (twoIndex >=0){
    result[index] += twoArr[twoIndex];
    if(result[index] > 9){
    result[index] = result[index] % 10;
    result[index-1] = 1;
    }
    index--;
    twoIndex--;
    }

    System.out.println(Arrays.toString(result));
    }
  • 相关阅读:
    django-搭建BBS关键点总结
    关于django中input标签中file类型以及开路由
    Bzoj1115 石子游戏Kam
    HDU1907 John
    HDU2509 Be the Winner
    洛谷P1082 同余方程
    POJ1065 Area
    Vijos1889 天真的因数分解
    Bzoj2440 完全平方数
    Bzoj2705 Longge的问题
  • 原文地址:https://www.cnblogs.com/dongma/p/13233167.html
Copyright © 2011-2022 走看看