随笔- 509  文章- 0  评论- 151  阅读- 22万 

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   zhuli19901106  阅读(252)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示