您的位置:首页 > 编程语言

九度机试笔记20170903--1

2017-09-03 11:46 330 查看
题目1488:百万富翁问题

#include <iostream>
using namespace std;

int main()
{
cout<<10*30<<' ';
int i=1, sum=0;
for(int j=0; j<30; j++){
sum+=i;
i*=2;
}
cout<<sum<<endl;
return 0;
}


题目1489:计算两个矩阵的乘积

#include <iostream>
using namespace std;
int main()
{
int a[2][3]={0};
int b[3][2]={0};
int sum = 0, i, j, k;
while(cin>>a[0][0]>>a[0][1]>>a[0][2]){
for(i=1; i<2; i++){
for(j=0; j<3; j++){
cin>>a[i][j];
}
}
for(i=0; i<3; i++)
for(j=0; j<2; j++)
cin>>b[i][j];
for(i=0; i<2; i++){
for(j=0; j<2; j++){
for(k=0; k<3; k++){
sum+=a[i][k]*b[k][j];
}
cout<<sum<<(j==0?" ":" \n");
sum = 0;
}
}
}
return 0;
}


注意:虽然题目没有明确说明有多对矩阵乘积,但是写的时候需要考虑。(3次AC)

题目1490:字符串链接

#include <stdio.h>
#include <string.h>

void MyStrcat(char dstStr[],char srcStr[])
{
int len = strlen(dstStr);
int len1 = strlen(srcStr);
for(int i = 0; i<len1; i++)
dstStr[len+i]=srcStr[i];
dstStr[len+len1]='\0';
}
int main()
{
char d[2000]={0};
char s[2000]={0};
while(scanf("%s",d)!=EOF){
scanf("%s",s);
MyStrcat(d,s);
printf("%s\n",d);
memset(d,0,2000);
memset(s,0,2000);
}
return 0;
}


注意:这里我犯了一个错误,使用了while(scanf(“%s”,d)),需要将该语句修改为:while(scanf(“%s”,d)!=-1)或while(scanf(“%s”,d)!=EOF),不然会导致循环太多次,报错Output Limit Exceed。(2次AC)

题目1055:数组逆置

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
string str;
while(cin>>str){
reverse(str.begin(),str.end());
cout<<str<<endl;
}
return 0;
}


还有几种字符串反转的办法,见http://blog.csdn.net/szu_aker/article/details/52422191

题目1056:最大公约数

#include <iostream>
using namespace std;

int main()
{
int a, b;
while(cin>>a>>b)
{
if(a>b)
{
int tmp = b, b = a, a = tmp;
}
if(b%a==0) cout<<a<<endl;
else
{
for(int i = a/2; i>0; i--)
{
if(a%i==0 && b%i==0)
{
cout<<i<<endl;
break;
}
}
}
}
return 0;
}


办法比较笨,其实还有老师曾经教过的辗转相除法,竟然想不起来了(T▽T),下面是找的简洁的代码。

#include<stdio.h>
void main()   /*  辗转相除法求最大公约数和最小公倍数 */
{
int m, n, a, b, t, c;
printf("Input two integer numbers:\n");
scanf("%d%d", &a, &b);
m=a;   n=b;
while(b!=0)  /* 余数不为0,继续相除,直到余数为0 */
{ c=a%b; a=b;  b=c;}
printf("The largest common divisor:%d\n", a);
printf("The least common multiple:%d\n", m*n/a);
}


题目1057:众数

#include <string.h>
#include <iostream>
using namespace std;

int main()
{
int table[
b047
11]={0};
int tmp;
while(cin>>tmp)
{
table[tmp]++;
for(int i=0; i<19; i++){
cin>>tmp;
table[tmp]++;
}
int res = 1;
for(int i = 0; i<11; i++)
if(table[i]>table[res])
res = i;
cout<<res<<endl;
memset(table,0,11*sizeof(int));
}
return 0;
}


题目1050:完数

#include <iostream>
using namespace std;

int main()
{
int n;
while(cin>>n)
{
if(n>=6){
cout<<6;
for(int i = 7; i<=n; i++){
int sum = 1;
for(int j = 2; j< i/j; j++)
{
if(i%j==0){
sum+=j;
sum+=i/j;
}
}
if(sum==i)
cout<<' '<<i;
}
cout<<endl;
}
else
{
cout<<endl;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  九度 编程 机试