0
已解决
6780 数字变身
经验值:1200 时间限制:1000毫秒 内存限制:128MB
题目描述 Description
有整数m,n,现在请你计算将m变成n需要变化几位。
输入描述 Input Description
共1行:空格隔开的两个整数
m n
输出描述 Output Description
需要改变的整数
样例输入 Sample Input
【样例输入1】
29 15
【样例输入2】
1 2
样例输出 Sample Output
【样例输出1】
2
【样例输出2】
2
数据范围及提示 Data Size & Hint
m,n范围在[-2147483648, 2147483647]之间
【样例说明】
29的二进制可表示为11101,15的二进制可以表示为01111,所以需要改变两位。
我写了两种方式的代码:
错误代码1 WA 40分:
#include<bits/stdc++.h>
using namespace std;
long long a,b,x[1005],y[1005],t,cnt,ans,sum;
int main(){
cin>>a>>b;
while(a){
x[++cnt]=a%2;
a/=2;
}
while(b){
y[++ans]=b%2;
b/=2;
}
for(int i=max(cnt,ans);i>=1;i--){
if(x[i]!=y[i]){
sum++;
}
}
cout<<sum;
return 0;
}
错误代码2 WA 30分:
#include<bits/stdc++.h>
using namespace std;
long long a,b,ans;
string x,y;
bool fa,fb;
int main(){
cin>>a>>b;
if(a<0){
fa=1;
a=abs(a);
}
if(b<0){
fb=1;
b=abs(b);
}
while(a){
char o=(a&1)+'0';
x=o+x;
a>>=1;
}
while(b){
char o=(b&1)+'0';
y=o+y;
b>>=1;
}
if(x.size()>y.size()){
for(int i=1;i<=x.size()-y.size();i++){
y='0'+y;
}
}else{
for(int i=1;i<=y.size()-x.size();i++){
x='0'+x;
}
}
// cout<<x<<' '<<y<<endl;
for(int i=0;i<x.size();i++){
if(x[i]!=y[i]){
ans++;
}
}
ans+=abs(fa-fb);
cout<<ans;
return 0;
}
求大佬指点
熊潇然在2022-11-06 10:11:04追加了内容
d
熊潇然在2022-11-06 20:43:11追加了内容
d
熊潇然在2022-11-07 09:35:39追加了内容
@姜宇轩 你能顺便帮我看一下这一题吗
熊潇然在2022-11-07 12:43:45追加了内容
@张世贤 按你的方法TLE 40分
#include<bits/stdc++.h>
using namespace std;
long long a,b,ans;
int main(){
cin>>a>>b;
a^=b;
while(a){
if(a&1) ans++;
a>>=1;
}
cout<<ans;
return 0;
}
熊潇然在2022-11-09 16:10:25追加了内容
@张世贤 !!!
熊潇然在2022-11-09 16:10:31追加了内容
@张世贤 !!!
熊潇然在2022-11-09 16:10:35追加了内容
@张世贤 !!!
熊潇然在2022-11-12 14:58:57追加了内容
怎么做!大佬快来!
@姜宇轩 @汪宇航 @各位大佬 @各位老师!
熊潇然在2022-11-13 09:54:25追加了内容
怎么把负十进制转二进制!!!
熊潇然在2022-11-16 21:36:02追加了内容
@张世贤
n是什么???
#include<bits/stdc++.h>
using namespace std;
long long a,b,ans;
int main(){
cin>>a>>b;
a^=b;
while(a){
a&=/* n是啥??? */;
ans++;
}
cout<<ans;
return 0;
}
0
0
0
0
0
0
0
0
0
0
0
