Careercup - Microsoft面试题 - 6543214668414976

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 }

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3721317.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值