swift 1-N求和 两种方式

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        func sum(_ n:Int) -> Int{
            var a = 0
            for i in 0 ... n {
                a += i
            }
            return a
        }
        
        
        func recursion (_ number :Int) -> Int {
            print("---\(number)---")
            if(number == 1){
                return 1
            } else {
                print("(\(number)) + recursion(\(number-1))")
                return number + recursion(number-1)
            }
        }
        print(recursion(10))
    }
}
---10---
(10) + recursion(9)
---9---
(9) + recursion(8)
---8---
(8) + recursion(7)
---7---
(7) + recursion(6)
---6---
(6) + recursion(5)
---5---
(5) + recursion(4)
---4---
(4) + recursion(3)
---3---
(3) + recursion(2)
---2---
(2) + recursion(1)
---1---
55

你可能感兴趣的:(swift 1-N求和 两种方式)