题目:
一个人a年b月c日出生,a,b,c三数的乘积为428575,这个人是什么时候出生的?
用Object-C实现:
//一个人a年b月c日出生,a,b,c三数的乘积为428575,这个人是什么时候出生的? - (void)p_caclueYearMonthDay { //获取当前年月日 NSDate *date = [NSDate date]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"YYYY"]; NSInteger currentYear = [[formatter stringFromDate:date] integerValue]; [formatter setDateFormat:@"MM"]; NSInteger currentMonth= [[formatter stringFromDate:date] integerValue]; [formatter setDateFormat:@"DD"]; NSInteger currentDay = [[formatter stringFromDate:date] integerValue]; ///每月基本天数 NSMutableArray *dayArray= [NSMutableArray arrayWithArray:@[@31,@28,@31,@30,@31]]; ///遍历年 for (NSInteger year = 0; year <= currentYear; ++year) { ///是否闰年,修改2月天数 if (year % 4 == 0) { [dayArray setObject:@29 atIndexedSubscript:1]; } else { [dayArray setObject:@28 atIndexedSubscript:1]; } //根据是否是当前年判断有没有12个月 NSInteger maxMonth = ((year == currentYear)?currentMonth:12); ///遍历月 for (NSInteger month = 1; month <= maxMonth; ++month) { //根据是否是当前年月判断这个月有多少天 NSInteger maxDay = ((year == currentYear && month == currentMonth)?currentDay:[dayArray[month-1] integerValue]); ///遍历日 for (NSInteger day = 1; day <= maxDay; ++day) { if (428575 == (year * month * day)) { NSLog(@"这个人出生在%ld年%ld月%ld日",(long)year,(long)month,(long)day); //break; //不能用break;的原因是因为可能会存在多个结果 } } } } }
用swift实现:
//一个人a年b月c日出生,a,b,c三数的乘积为428575,这个人是什么时候出生的? func calueYearMonthDay() { //获取当前年月日 let currentdate = NSDate() let formatter = DateFormatter() formatter.dateFormat = "YYYY" let currentYear : Int = Int(formatter.string(from: currentdate as Date))! formatter.dateFormat = "MM" let currentMonth : Int = Int(formatter.string(from: currentdate as Date))! formatter.dateFormat = "DD" let currentDay : Int = Int(formatter.string(from: currentdate as Date))! //每月基本天数 let dayArray = NSMutableArray.init(array: [31,28,31,30,31]) //遍历年 for year in 0...currentYear { //判断是否闰年 dayArray[1] = ( year % 4 == 0 ) ? 29 : 28 ///根据是否是当前年判断有没有12个月 let maxMonth : Int = (year == currentYear ? currentMonth : 12) //遍历月 for month in 1...maxMonth { //根据是否是当前年月判断这个月有多少天 let maxDay = ((year == currentYear && month == currentMonth) ? currentDay : ((dayArray[month-1]) as! Int)) //遍历日 for day in 1...maxDay { if (428575 == year * month * day) { print("这个人出生在\(year)年\(month)月\(day)日") } } } } }