最近比较火的一道题(传送门),看见园友们的谈论(传送门1 传送门2),都是从1到100的扫描,我想说说的另一种想法。
可以把这道题转换成给100个人发纸牌的游戏,每人所报的就是纸牌上写的东西。
纸牌发放时有优先级的:
有纸牌的同学就不再给了。
假设三个数字分别为a,b,c,那么以上的优先级的特点就是:
10以内的最小公倍数比较好计算,也不用从1到100的扫描,感觉会更快一些。
跟文艺青年的代码做了一下对比:
附源码(有点乱,多担待):
class="code_img_closed" src="/Upload/Images/2014050422/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('fb875309-3f07-4277-b34e-dce0b2139d52',event)" src="/Upload/Images/2014050422/2B1B950FA3DF188F.gif" alt="" />class Program { static void Main(string[] args) { //string[] s1 = Console.ReadLine().Split(','); Test("3,5,7"); Test("2,4,8"); Test("3,6,8"); Console.ReadKey(); } static void Test(string str) { Console.WriteLine(str); string[] s1 = str.Split(','); int[] s2 = new int[] { int.Parse(s1[0]), int.Parse(s1[1]), int.Parse(s1[2]) }; string[] r1 = Test1(s2); string[] r2 = Test2(s2); bool flag = true; for (int i = 0; i < 100; i++) { if (r1[i] != r2[i]) { flag = false; break; } } if(flag) { Console.WriteLine("结果相等"); } else { Console.WriteLine("结果不相等"); } DateTime dt = DateTime.Now; for (int i = 0; i < 10000; i++) { Test1(s2); } TimeSpan ts = DateTime.Now - dt; Console.WriteLine("文艺青年耗时:"+ts.TotalMilliseconds); DateTime dt2 = DateTime.Now; for (int i = 0; i < 10000; i++) { Test2(s2); } TimeSpan ts2 = DateTime.Now - dt2; Console.WriteLine("屌丝青年耗时:" + ts2.TotalMilliseconds); Console.WriteLine(); } private static string[] Test1(int[] a) { string[] result = new string[100]; for (int i = 1; i <= 100; i++) { result[i - 1] = (i % a[0] == 0 ? "Fizz" : "") + (i % a[1] == 0 ? "Buzz" : "") + (i % a[2] == 0 ? "Whizz" : "") + ((i % a[0] != 0 && i % a[1] != 0 && i % a[2] != 0) ? i.ToString() : ""); } for (int i = 0; i < 10; i++) { result[a[0] * 10 + i - 1] = result[i * 10 + a[0] - 1] = "Fizz"; } return result; } private static string[] Test2(int[] a) { string[] result = new string[100]; for (int i = 0; i < 10; i++) { result[a[0] * 10 + i - 1] = result[i * 10 + a[0] - 1] = "Fizz"; } comp(result, nlcm(a, 3), "FizzBuzzWhizz"); comp(result, lcm(a[0], a[1]), "FizzBuzz"); comp(result, lcm(a[0], a[2]), "FizzWhizz"); comp(result, lcm(a[1], a[2]), "BuzzWhizz"); comp(result, a[0], "Fizz"); comp(result, a[1], "Buzz"); comp(result, a[2], "Whizz"); for (int i = 1; i <= 100; i++) { if (string.IsNullOrEmpty(result[i - 1])) { result[i - 1] = i.ToString(); } } return result; } static void comp(string[] result, int temp, string str) { for (int i = 1; i * temp <= 100; i++) { if (string.IsNullOrEmpty(result[i * temp - 1])) { result[i * temp - 1] = str; } } } static int gcd(int a, int b) { if (a < b) swap(ref a, ref b); if (b == 0) return a; else return gcd(b, a % b); } private static void swap(ref int a, ref int b) { int c = a; a = b; b = c; } static int ngcd(int[] a, int n) { if (n == 1) return a[0]; return gcd(a[n - 1], ngcd(a, n - 1)); } static int lcm(int a, int b) { return a * b / gcd(a, b); } static int nlcm(int[] a, int n) { if (n == 1) return a[0]; else return lcm(a[n - 1], nlcm(a, n - 1)); } }View Code