c++ - 为什么我在 CodeChef Closest Divisor 程序中出现错误?
问题描述
我正在尝试解决 Codechef 最近除数问题
我不知道为什么它给了我错误的解决方案。
问题陈述是
给定两个整数 A 和 B,找出能被 B 整除的最大数 ≤A。
输入:输入由两行组成。输入的第一行包含一个整数 A。输入的第二行包含一个整数 B。
输出:在单独的行中打印完全可被 B 整除的最大整数 ≤A。
约束 1≤B≤A≤10^9
这是我的代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
void file_i_o() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("Input.txt","r",stdin);
freopen("Output.txt","w",stdout);
#endif
}
int main(int argc, char** argv) {
file_i_o();
//write your code here
ll A,B;
cin>>A>>B;
ll q = A/B;
ll n1 = B*q;
ll n2 = 0;
if(A*B > 0) {
n2 = B*(q+1);
} else {
n2 = B*(q-1);
}
if(abs(A-n1) < abs(A-n2)) {
if(n1<=A) {
cout<<n1;
}
} else {
if(n2<=A) {
cout<<n2;
}
}
return 0;
}
解决方案
我认为你使问题复杂化了。我只是看着问题。它不需要那么复杂。
这是我的解决方案(AC):
void solve(){
int a, b;
read(a, b);
cout << a / b * b << endl;
}
如果你硬要找出问题,我只能说A * B > 0
永远都是真的,没有必要去判断,也许就是问题所在。
推荐阅读
- javascript - 用于时刻日期的自定义 js-data 格式化程序
- node.js - Node.js 在缩小的 npm 包中崩溃/退出,没有任何错误消息,如何调试?
- python-3.x - 如何获取不包含由下划线分隔的最后两个单词的字符串的一部分
- ios - Swift - 推送和弹出 UIViewcontroller 不起作用
- amazon-web-services - 通过 API 与 Alexa Skill 通信
- react-native - react native 中按钮样式的常用技术?
- swift - Swift:从网络请求中初始化模型数据 [weatherApp]
- r - 更新闪亮的标签
- java - RESTeasy 和 @MultipartForm 、服务器和客户端
- python - 列表可以放在同一个列表中吗?