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));
    }
  • 相关阅读:
    mysql索引
    数据库修复
    数据库取值 三级分类后台遍历
    创建数据库!
    mysql按条件 导出sql
    nodejs 简单安装环境
    C++ 性能剖析 (一)
    C++ 性能剖析 (二):值语义 (value semantics)
    JavaScript Nested Function 的时空和身份属性
    C++ Reference 的“三位一体”诠释
  • 原文地址:https://www.cnblogs.com/dongma/p/13233167.html
Copyright © 2011-2022 走看看