zoukankan      html  css  js  c++  java
  • leetcode第二题

    题目描述:

    给定两个非空数组[1, 2, 3] [4, 5, 6]

    将两个数组中的数倒序组合成一个数字并相加 321+654=975

    返回数组[5, 7, 9]

    代码实现(Vue脚手架环境)

        mounted() {
          let res = this.add([1, 2, 3], [4, 5, 6])
          console.log(res);
        },
        methods: {
          add(arr1, arr2) {
            let num1 = 0
            let num2 = 0
            for(let i=0; i<arr1.length; i++){
              num1 += arr1[i] * Math.pow(10, i)
            }
            console.log(num1);
            for(let i=0; i<arr2.length; i++){
              num2 += arr2[i] * Math.pow(10, i)
            }
            console.log(num2);
            let num3 = num1 + num2
            console.log(num3);
            let arr = num3.toString().split("")
            return arr.reverse().map(Number);
          }
        }

    笔记:

    难点在于将最后相加得到的数字类型转换为存储数字的数组

    1.num3.toString()将num3转换为字符串

    2.split("")将字符串转为存储字符串类型数字的数组

    3.reverse()将数组顺序倒转

    4.map(Number)方法可以将数组中每一个值转换为数字并返回一个新数组

  • 相关阅读:
    Andriod调试桥
    抓包工具charles的使用
    测试常用工具
    Indentation error codes
    Cmder 中文乱码的解决方法
    修改Cmder命令提示符
    统计单词出现的字数
    将字串内容输出到文件
    python数据实例str
    python语法检查工具
  • 原文地址:https://www.cnblogs.com/lilililiwang/p/14751245.html
Copyright © 2011-2022 走看看