Skip to content

Instantly share code, notes, and snippets.

@marciok
Last active April 4, 2016 07:45
Show Gist options
  • Select an option

  • Save marciok/33adbf5ba598f8a682b41ab7d76690b7 to your computer and use it in GitHub Desktop.

Select an option

Save marciok/33adbf5ba598f8a682b41ab7d76690b7 to your computer and use it in GitHub Desktop.
Addition without the plus operator
//
// Addition without `+` operator
//
func sum(n1: Int, n2: Int) -> Int {
let result = n1 ^ n2
let carry = (n1 & n2) << 1
if carry != 0 {
return sum(result, n2: carry)
}
return result
}
let r = sum(7, n2: 1)
/*
Step by step:
'^'
00111 = 7
00001 = 1
-----
00110 = 6
'&'
00111 = 7
00001 = 1
-----
00001 = 1
'<< 1'
00010 = 2
=== sum(6, n2: 2) ===
'^'
00110 = 6
00010 = 2
-----
00100 = 4
'&'
00110 = 6
00010 = 2
-----
00010 = 2
'<<' 1
00100 = 4
=== sum(4, n2: 4) ===
'^'
00100 = 4
00100 = 4
-----
00000 = 0
'&'
00100 = 4
00100 = 4
-----
00100 = 4
'<<' 1
01000 = 8
=== sum(0, n2: 8) ===
'^'
00000 = 0
01000 = 8
-----
01000 = 8
'&'
00000 = 0
01000 = 8
-----
00000 = 0
'<<' 1
00000 = 0
=== sum(8, n2: 0) ===
Result = 8
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment