Skip to content

Instantly share code, notes, and snippets.

@QuadFlask
Created March 31, 2016 14:24
Show Gist options
  • Save QuadFlask/702d74dcae85ef9d7f115dd51108fd12 to your computer and use it in GitHub Desktop.
Save QuadFlask/702d74dcae85ef9d7f115dd51108fd12 to your computer and use it in GitHub Desktop.
[CodeWars] Add big numbers

겁나게 긴 숫자 덧셈기를 만드는 문제

최대한? 펑셔널하게 해보고 싶었는데 오히려 코드가 길어진듯...

MySolution

function add(n1, n2) {
	if (n1.length < n2.length) {
		var t = n1;
		n1 = n2;
		n2 = t;
	}

	return [n1
		.split('')
		.reverse()
		.map((a,i)=> (~~a + ~~n2[n2.length - i - 1]))
		.reduce((a,b)=> {
			b += a[1];
			a[1] = 0;
			if(b >= 10){
				b %= 10;
				a[1] = 1;
			}
			a[0] = b + a[0];
			return a;
		},['', 0])
		.reverse()
		.join('')]
		.map(s=>s[0]=='0'?s.substr(1):s)[0];
}

Best Practice

function add (a, b) {
  var res = '', c = 0
  a = a.split('')
  b = b.split('')
  while (a.length || b.length || c) {
    c += ~~a.pop() + ~~b.pop()
    res = c % 10 + res
    c = c > 9
  }
  return res
}

배열로 만들고 하나씩 팝(1의 자리부터 차례대로!!! 이렇게 하면 되는군)해서 덧셈을 하고 캐리를 저장하고 이러면 되네;; 너무 어렵게 생각한거 같음...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment