试题A:握手问题
1、题目分析

分析:n人依次握手,第一个人要握(n-1)次,第二个人要握(n-2)次……,第五十个人要握一次。
故握手总次数f(n) =(n-1)+(n-2)+(n-3)+……+1 = (n-1+1) * (n-1)/2 = n * (n-1)/2
本题结果应为f(50)-f(7)
2、代码
#include<iostream>
using namespace std;
int main()
{
int ans = (50 * 49) / 2 - (7 * 6) / 2;
cout << ans << endl;
return 0;
}

试题B:小球反弹
1、题目分析

分析:设小球运动时间为t,在x轴方向运动了p个来回,在y轴方向运动了q个来回。
则,x方向运动距离 2px=t * dx,y方向运动距离2py=t * dy
两式相比,可得p/q=(dx * y)/(dy * x),即p=dx*y(约分后)
t=2px/dx,x=t * sqrt(dx2+dy2)
2、代码
#include<iostream>
#include<cmath>
using namespace std;
//辗转相除,最大公因数
int g(int a, int b)
{
return b == 0 ? a : g(b, a % b);
}
int main()
{
int x = 343720, y = 233333, dx = 15, dy = 17;
int p = y * dx, q = x * dy;
int a =g(p, q);
p /= a;
double t = 2 * p * x / dx;
double ans = t * sqrt(dx * dx + dy * dy);
printf("%.2lf", ans);
return 0;
}

试题C:好数
1、题目分析



分析:通过标志位tag来判断x的奇数位和偶数位,循环x的每一位来进行判断。
2、代码
#include<iostream>
using namespace std;
bool check(int x)
{
int tag = 1;//判断奇偶位
while (x)
{
if (tag % 2 == 0 && x % 10 % 2 != 0)
return false;
else if (tag % 2 != 0 && x % 10 % 2 == 0)
return false;
else
{
tag++;
x /= 10;
}
}
if (x == 0)
return true;
}
int main()
{
int n; cin >> n;
int ans = 0;
for (int i = 1; i <= n; i++)
{
if (check(i))
{
ans++;
}
}
cout << ans << endl;
return 0;
}
试题D:R格式
1、题目分析


分析:先根据题意进行编写代码,暴力求解
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int n;
double d;
cin >> n; cin >> d;
long x = 1;
while (n--)
{
x *= 2;
}
double ans = d * x;
cout << round(ans) << endl;
return 0;
}

当n过大时,循环求2n的时间复杂度为O(n),效率太低,进行优化更改(高精度算法):高精度算法介绍
使用高精度算法:
将字符串d倒序存入数组中,令数组中的每一位与2相乘循环乘n次。
2、代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
//高精度算法
int n;
string d;
cin >> n >> d;
int a[15000] = { 0 };
//反转字符串
reverse(d.begin(), d.end());
//确定小数点位置
int pos = d.find('.');
//删除d中的小数点
d.erase(pos, 1);
int len = d.size();
//将d存入a中
for (int i = 0; i < len; i++)
a[i] = d[i] - '0';
//高精度*低精度
for (int i = 0; i < n; i++)
{
for (int j = 0; j < len; j++)
{
a[j] *= 2;
}
//进位
for (int j = 0; j < len; j++)
{
if (a[j] >= 10)
{
a[j + 1]++;
a[j] %= 10;
if (j + 1 == len)
len++;
}
}
}
if (a[pos - 1] >= 5)
a[pos]++;
for (int i = len - 1; i >= pos; i--)
cout << a[i];
return 0;
}

2887

被折叠的 条评论
为什么被折叠?



