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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)