2014-05-11 02:56

题目链接

原题:

Write a function called FooBar that takes input integer n and prints all the numbers from 1 upto n in a new line. If the number is divisible by 3 then print "Foo", if the number is divisible by 5 then print "Bar" and if the number is divisible by both 3 and 5, print "FooBar". Otherwise just print the number. 
for example FooBar(15) should print as follows: 
1 
2 
Foo 
4 
Bar 
Foo 
7 
8 
Foo 
Bar 
11 
Foo 
13 
14 
FooBar 

I know, easy right? ;)

题目:从1到n的整数,如果被3整除就输出Foo,如果被5整除就输出Bar,如果是公倍数就输出FooBar,否则直接输出原数。

解法:这题有什么陷阱?n可以是大数吗?n可以小于1吗?如果是实际面试,肯定要问清楚的。在此,我就按最简单的处理了。在这种题目上自找麻烦是没意义的。

代码:

 1 // http://www.careercup.com/question?id=6543214668414976
 2 #include <iostream>
 3 #include <sstream>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     int n;
 9     int i;
10     
11     while (cin >> n && n > 0) {
12         for (i = 1; i <= n; ++i) {
13             if (i % 3) {
14                 if (i % 5) {
15                     cout << i;
16                 } else {
17                     cout << "Bar";
18                 }
19             } else {
20                 if (i % 5) {
21                     cout << "Foo";
22                 } else {
23                     cout << "FooBar";
24                 }
25             }
26             cout << endl;
27         }
28     }
29     
30     return 0;
31 }

 

 posted on 2014-05-11 03:12  zhuli19901106  阅读(252)  评论(0编辑  收藏  举报