前几天参加新浪的面试,遇到俩个比较有意思的面试题,特写出来跟大家分享一下
1.找规律的一组数, 1,1,2,3,5,8...n;其实就是斐波那契数列
解决办法有很多,递归很简单:
<示例代码>
int fib(int n){
if (n == 1 || n == 2) {
return 1;
}else{
return fib(n - 1) + fib(n - 2);
}
}
int main(int argc, const char * argv[]) {
int n;
scanf("%d",&n);
printf("%d\n",fib(n));
printf("%d\n",ll(n));
return 0;
}
2.统计(1! + (1! + 3!) +...+ (1! + ... +(2 * n - 1)!))
<>@interface ViewController ()
@end
@implementation ViewController
/统计(1! + (1! + 3!) +...+ (1! + ... +(2 * n - 1)!))/
- (void)viewDidLoad {
[super viewDidLoad];
NSInteger sum4 = 0;
NSInteger n = 3;
sum4 = [self sumOfOriginEquation:n];
NSLog(@"%zd",sum4);
}
//外递归 - (NSInteger)sumOfOriginEquation: (NSInteger)n{
if (n >= 1) { return [self sumOfPerEquation:n] + [self sumOfOriginEquation:n - 1]; }
else{return 0;
}
}
//内递归 - (NSInteger)sumOfPerEquation: (NSInteger)n{
NSInteger num1;
num1 = 1;
for (NSInteger i = 1; i <= (2 * n - 1); i++) { num1 *= i;
}
if (n == 1) {return 1;
}
return (num1 + [self sumOfPerEquation:(n - 1)]);
}