题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2116
题目大意就是给你两个k位数,然后相加,判断是否溢出。
思路:如果一正一负,那肯定不会溢出,其他情况就都转化为二进制来做,只要判断最后结果的位数就行了。
View Code
1 #include<iostream> 2 #include<string> 3 #include<algorithm> 4 using namespace std; 5 6 int main(){ 7 int k; 8 while(~scanf("%d",&k)){ 9 __int64 n,m; 10 scanf("%I64d%I64d",&n,&m); 11 if((n<0&&m>=0)||(n>=0&&m<0)){ 12 printf("WaHaHa\n"); 13 continue; 14 } 15 int tag=0; 16 if(n<=0&&m<=0){ 17 n=-1*n; 18 m=-1*m; 19 tag=1; 20 } 21 string s1="",s2="",s3=""; 22 int i,j,c=0,l=0; 23 while(n){ 24 s1+=n%2+'0'; 25 n/=2; 26 } 27 while(m){ 28 s2+=m%2+'0'; 29 m/=2; 30 } 31 for(i=0,j=0;i<s1.size()&&j<s2.size();i++,j++){ 32 l=(c+(s1[i]-'0'+s2[j]-'0'))%2; 33 s3+=l+'0'; 34 c=(c+s1[i]-'0'+s2[j]-'0')/2; 35 } 36 while(i<s1.size()){ 37 l=(c+(s1[i]-'0'))%2; 38 s3+=l+'0'; 39 c=(c+s1[i++]-'0')/2; 40 } 41 while(j<s2.size()){ 42 l=(c+(s2[j]-'0'))%2; 43 s3+=l+'0'; 44 c=(c+s2[j++]-'0')/2; 45 } 46 if(c)s3+=c+'0'; 47 reverse(s3.begin(),s3.end()); 48 if(tag&&s3.size()==k){ 49 //如果都是负数的话,当相加刚好位k位时,那么最小是最高位为1,其余都是0,否则就会溢出; 50 //比如(-15)+(-1)=10000,此时k为5,表示-16. 51 for(i=1;i<s3.size();i++){ 52 if(s3[i]=='1'){ 53 printf("Yes\n"); 54 break; 55 } 56 } 57 if(i==s3.size())printf("WaHaHa\n"); 58 }else if(s3.size()+1<=k){ 59 printf("WaHaHa\n"); 60 }else 61 printf("Yes\n"); 62 } 63 return 0; 64 }