趣味算法消消乐

93 阅读1分钟

大数相加

 const add = (a, b) => {
            const maxLength = Math.max(a.length, b.length)
            const overFlow = false
            for(let i = 1;  i <=  maxLength; i++){
                  const a = a[a.length-i]|| '0'
                  const b = a[b.length-i] || '0'
                  const c = parseInt(a) + parseInt(b) + overFlow ? '1' : '0'
                  overFlow =  c >= 10
                  newC = overFlow ? c - 10 : c
                  sum =  newC + sum
            }
            sum = overFlow ? '1' + sum : sum
            return sum
         }

两数相加

  const twoSum = (numbers, target) => {
            for(let i = 0; i <= numbers.length; i++){
                  const map = { }
                  const number = numbers[i]
                  const number2 = target - number
                  if(numbers in map ){
                        const number2Index = map[number2]
                        return [i, number2Index ]
                  }else{
                        map[number] = i
                  }
            } 
            return []
         }