Created
June 20, 2021 07:08
-
-
Save Aditi3/8e4f50b4459fa83b8a5b740c1a0cdc72 to your computer and use it in GitHub Desktop.
Implementing Power Function Using Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import UIKit | |
| //2^3 = 2 * 2 * 2 = 8 | |
| /* | |
| Stack | |
| 2 * power(2,2) | |
| 2 * power(2,1) | |
| 2 * power(2,0) | |
| ------ | |
| 2 * 4 | |
| 2 * 2 | |
| 2 * 1 | |
| */ | |
| func power(number: Int, n: Int) -> Int { | |
| // base case | |
| if n == 0 { | |
| return 1 | |
| } else { | |
| return number * power(number: number, n: n - 1) | |
| } | |
| } | |
| print(power(number: 2, n: 3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment