关于淘汰85%面试者的百度开发者面试题

题目描述:
依序遍历0到100闭区间内所有的正整数,如果该数字能被3整除,则输出该数字及‘*’标记;如果该数字能被5整除,则输出该数字及‘#’标记;如果该数字既能被3整除又能被5整除,则输出该数字及‘*#’标记。

忘了第一次从哪看见的了,刚才在  王奎MarkSaas博客里看见有人在讨论这个面试题。见到不少好的解题方法,记录下来。
我的解法:

#include <iostream>
using namespace std;
int main()
{

	for (int i = 0; i <= 100; i++)
	{
		if ((i % 3 == 0) ^ (i % 5 == 0))
		{
			if (i % 3 == 0)
				cout << i << '*'<<endl;
			else
				cout << i << '#'<<endl;
		}
		else if ((i % 3 == 0) && (i % 5 == 0))
			cout << i << "*#"<<endl;
	}
	return 0;
}
别人的:
/*
	@author marksaas
	@blog www.marksaas.com
	@time 2014-4-24
	timu依序遍历0到100闭区间内所有的正整数,如果该数字能被3整除,则输出该数字及‘*’标记;
	如果该数字能被5整除,则输出该数字及‘#’标记;如果该数字既能被3整除又能被5整除,则输出该数字及‘*#’标记。
*/
public class Baidu{
	public static void main(String[] args){
		for(int i=1;i<100;i++){
			if(i%3==0&&i%5==0){
				System.out.println(i+"*#");
				}else
				if(i%3==0){
					System.out.println(i+"*");
					}else
					if(i%5==0){
					System.out.println(i+"#");
					}
		}
	}
}

/*
	@author marksaas
	@blog www.marksaas.com
	@time 2014-4-24
	timu依序遍历0到100闭区间内所有的正整数,如果该数字能被3整除,则输出该数字及‘*’标记;
	如果该数字能被5整除,则输出该数字及‘#’标记;如果该数字既能被3整除又能被5整除,则输出该数字及‘*#’标记。
*/
public class Baidu{
	public static void Print(){
		String result="";
		for(int i=1;i<=100;i++){
			if(i%3==0){
				result=i+"*";
				if(i%5==0){
					result+="#";
				}
				System.out.println(result);
				continue;
			}else if(i%5==0){
				result=i+"#";
				System.out.println(result);
			}

		}

	}
	public static void main(String[] args){
		Print();
	}
}
表示不明觉厉
//个人主页:http://my.csdn.net/u012999424
#include<iostream>
#include<string>

using namespace std;

int main()
{
int add[7] = {3,2,1,3,1,2,3};
char c[6] = {'*','#','*','*','#','*'};
string all = "*#";
int i = 0;
int index = 0;
while((i += add[index]) <= 100)
{
if(index != 6)
{
cout << i << c[index] << endl;
index++;
}
else
{
cout << i << all << endl;
index = 0;
}
}
return 0;
}

经过优化的代码,
//http://blog.csdn.net/justmeing/article/details/24386071		
//商向下取整
		int threeIndex = (int) Math.floor(100/3);	
		int fiveIndex = (int) Math.floor(100/5);
		int bothIndex = (int) Math.floor(100/15);
		for(int i=1;i<=threeIndex;i++){
			if(i%5 != 0)
				System.out.println(3*i+"*");
			if(i<=fiveIndex && i%3 != 0)
				System.out.println(5*i+"#");
			if(i<=bothIndex)
				System.out.println(15*i+"*#");
		}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值