zoukankan      html  css  js  c++  java
  • 两个超长字符串相加

    思路:将他们转成int数组,然后按位相加,空间复杂度有点高,但时间复杂度为Max(O(M,N))

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String one = scanner.next();
                String two = scanner.next();
               addBigDight(one,two);
            }
        }
    
        private static void addBigDight(String one,String two){
            int oneLen = one.length();
            int twoLen = two.length();
            int resultLen = (oneLen > twoLen ? oneLen : twoLen ) + 1;
            int[] result = new int[resultLen];
            int oneIndex = oneLen - 1;
            int twoIndex = twoLen - 1;
            int index = 0;
            char[] oneChars = one.toCharArray();
            char[] twoChars = two.toCharArray();
    
            int[] oneArr = new int[oneLen];
            int[] twoArr = new int[twoLen];
    
            for (int i = 0; i < oneArr.length; i++) {
                oneArr[i] = oneChars[i] - '0';
            }
            for (int i = 0; i < twoChars.length; i++) {
                twoArr[i] = twoChars[i] - '0';
            }
            while (oneIndex >= 0 && twoIndex >= 0){
                result[index] += oneArr[oneIndex] + twoArr[twoIndex];
                if(result[index] > 9){
                    result[index] -= 10;
                    result[index + 1] = 1;
                }
                index++;
                oneIndex--;
                twoIndex--;
            }
            while (oneIndex >= 0){
                result[index] += oneArr[oneIndex];
                index++;
                oneIndex--;
            }
            while (twoIndex >= 0){
                result[index] += twoArr[twoIndex];
                index++;
                twoIndex--;
            }
            for (int i = index-1; i >= 0 ; i--) {
                System.out.print(result[i]);
            }
             System.out.println();
        }
    
    }
  • 相关阅读:
    VUE学习一,安装及Hello World
    609. 在系统中查找重复文件
    451. 根据字符出现频率排序
    面试题 10.02. 变位词组
    142. 环形链表 II
    面试题 16.24. 数对和
    151. 翻转字符串里的单词
    1207. 独一无二的出现次数
    80. 删除排序数组中的重复项 II
    1365. 有多少小于当前数字的数字
  • 原文地址:https://www.cnblogs.com/dongma/p/13258300.html
Copyright © 2011-2022 走看看