algorithmswithgo.com icon indicating copy to clipboard operation
algorithmswithgo.com copied to clipboard

DecToBase etc. doesn't test conversion of 0

Open thomasweitzel opened this issue 5 years ago • 1 comments

There's an important test case missing: DecToBase(0, ...). Same goes for BaseToDec.

In case of DecToBase(0, ...) an empty String is returned, which probably should be "0" instead.

I had to modify my recursive function - it now uses a helper function and duplicates some code:

const digits = "0123456789ABCDEF"

func _decToBase(dec, base int) string {
	if dec == 0 {
		return ""
	}
	digit := dec % base
	return _decToBase(dec/base, base) + string(digits[digit])
}

func DecToBase(dec, base int) string {
	digit := dec % base
	return _decToBase(dec/base, base) + string(digits[digit])
}

thomasweitzel avatar Feb 29 '20 21:02 thomasweitzel

Thanks! I'll add a test case for this and amend the video to address it.

joncalhoun avatar Mar 03 '20 19:03 joncalhoun