zoukankan      html  css  js  c++  java
  • 两个大数相乘笔试题目

    面试中遇到的笔试题目,手写两个大数相乘,不能用BigInteger (Java)

    /**
     * @Title: Test
     * @ProjectName client
     * @date 2019/11/1413:53
     */
    public class Test {
        public static void main(String[] args) {
            String multiply1 = multiply("200", "200");
            System.out.println(multiply1);
        }
        /**
         * 01234  数组索引
         * 400      第一次循环
         *  000     第二次循环
         *   000    第三次循环
         * 公式:AB*CD  =  AC (BC+ AD) BD
         * 67*89 = 6*8(7*8 + 6*9)7*9
         * 67*89 = 48(110)63
         * 63进6剩余3
         * 110变成116,满十进位,进行11,剩余6,
         * 48变成59。所以: 5963
         * 参考博客: https://blog.csdn.net/outsanding/article/details/79472376
         * @param num1
         * @param num2
         * @return
         */
        public static String multiply(String num1, String num2) {
            int num1_len = num1.length();
            int num2_len = num2.length();
            int[] numArr = new int[num1_len + num2_len];
            for (int i = 0; i < num1_len; i++) {
                int a = num1.charAt(i) - '0';
                for (int j = 0; j < num2_len; j++) {
                    int b = num2.charAt(j) - '0';
                    numArr[i + j] += a * b;
                }
            }
            // 从个位数向前一位进位
            for (int i = numArr.length - 1; i > 0; i--) {
                numArr[i - 1] += numArr[i] / 10;
                numArr[i] = numArr[i] % 10;
            }
            // 结果拼接
            String ret = "";
            for (int i = 0; i < numArr.length - 1; i++) {
                ret += numArr[i];
            }
            return ret;
        }
    }
    

      

  • 相关阅读:
    QQ企业邮箱+Spring+Javamail+ActiveMQ(发送企业邮件)
    Notepad++使用图解
    Sublime Text 2安装图解
    IDE UltraEdit 图文激活+安装教程
    光猫与普通的家用猫
    通过Java Api与HBase交互(转)
    HBase配置性能调优(转)
    HBase Java API类介绍
    hbase shell基础和常用命令详解(转)
    HBase体系结构(转)
  • 原文地址:https://www.cnblogs.com/412013cl/p/11858145.html
Copyright © 2011-2022 走看看