Add Subtract Coding Problem

Posted by Henry Du on Sunday, November 29, 2020

Add Subtract Coding Problem

Problem

Write a function addSubtract to meet the requirement that, it will alternately adds and subtracts carried parameters.

For example:

add_subtract(7) -> 7

add_subtract(1)(2)(3) -> 1 + 2 - 3 -> 0

add_subtract(-5)(10)(3)(9) -> -5 + 10 - 3 + 9 -> 11

Solution

The idea is to have a addSubtract struct to keep tracking the last add/subtract result and the count of function calls. If the count is even number, then use subtract operation, otherwise, use add operation.

The following is a sample go code. You may also try it in go playground.

package main

import (
	"fmt"
)

type addSubtract struct {
	value      int
	callCounts int
}

func (a addSubtract) Reset() {
	a.callCounts = 0
}

func (a addSubtract) Value() int {
	return a.value
}

func (a addSubtract) AddSubtract(n int) addSubtract {
	if a.callCounts == 0 {
		return addSubtract{
			value:      n,
			callCounts: a.callCounts + 1,
		}
	}
	if a.callCounts%2 == 0 {
		return addSubtract{
			value:      a.value - n,
			callCounts: a.callCounts + 1,
		}
	}
	return addSubtract{
		value:      a.value + n,
		callCounts: a.callCounts + 1,
	}
}

func main() {
	as := addSubtract{}

	fmt.Println(as.AddSubtract(7).Value())
	as.Reset()

	fmt.Println(as.AddSubtract(1).AddSubtract(2).AddSubtract(3).Value())
	as.Reset()

	fmt.Println(as.AddSubtract(-5).AddSubtract(10).AddSubtract(3).AddSubtract(9).Value())
}