說實話這道題中的挺無語的,本來可以是水題,但是當時寫的時候就想的比較複雜,long long 數據類型本來就包過符號,我把它想成那個用字符串型,把題目複雜化了
題目鏈接:A+B Again
AC代碼:
【c實現】
#include<iostream>
using namespace std;
typedef long long ll;
int main()
{
ll a,b;
while(~scanf("%llX%llX",&a,&b))
{
if(a+b>=0)
printf("%llX",a+b);
else
printf("-%llX",-(a+b));
cout<<endl;
}
return 0;
}
【C++】:
#include<iostream>
#include<iomanip>
using namespace std;
typedef long long ll;
int main()
{
ll a,b;
while(cin>>hex>>a>>b)
{
if(a+b>=0)
cout<<hex<<uppercase<<a+b<<endl;
else
cout<<hex<<uppercase<<'-'<<-(a+b)<<endl;
}
return 0;
}
可以通過字符串來處理:但是我失敗了;有一個朋友成功了,附上代碼:
#include<stdio.h>
#include<string.h>
long long fun1(char *a)
{
long long b=0,len,i=0;
len=strlen(a);
if(a[0]=='-'||a[0]=='+')
{
i=1;
}
while(i!=len)
{
if(a[i]<'0'||(a[i]>'9'&&a[i]<'A')||a[i]>'Z')
i++;
b=b*16;
switch(a[i])
{
case 'A':b=b+10;break;
case 'B':b=b+11;break;
case 'C':b=b+12;break;
case 'D':b=b+13;break;
case 'E':b=b+14;break;
case 'F':b=b+15;break;
default:b=b+a[i]-48;
}
i++;
}
if(a[0]=='-')
b=b*(-1);
return b;
}
void fun2(long long num)
{
char b[17];
int i,j;
i=-1;
if(num<0)
{ printf("-");
num=num*(-1);
}
if(num==0)
printf("0\n");
else
{
while(num/16)
{i++;
switch(num%16)
{
case 10:b[i]='A';break;
case 11:b[i]='B';break;
case 12:b[i]='C';break;
case 13:b[i]='D';break;
case 14:b[i]='E';break;
case 15:b[i]='F';break;
default:b[i]=num%16+48;
}
num=num/16;
}
if(num%16!=0)
{i++;
switch(num%16)
{
case 10:b[i]='A';break;
case 11:b[i]='B';break;
case 12:b[i]='C';break;
case 13:b[i]='D';break;
case 14:b[i]='E';break;
case 15:b[i]='F';break;
default:b[i]=num%16+48;
}
}
for(;i>=0;i--)
printf("%c",b[i]);
printf("\n");
}
}
int main()
{
char a[16],b[16];
while(~scanf("%s %s",a,b))
{
long long num;
num=fun1(a)+fun1(b);
fun2(num);
}
return 0;
}
不得不說這個大佬的基本功,太強了;
下面附加不同進制數從鍵盤輸入:
【c++】:
默認進制
cin
or cout
在默認情況下按照十進制輸入輸出
八進制
要使輸入爲八進制數,首先切換至八進制輸入
cin >> oct;
//接下里就可以輸入八進制數了
cin >> a; // a 是八進制數
十六進制
要使輸入爲十六進制數,首先切換至十六進制輸入
cin >> hex;
//接下里就可以輸入十六進制數了
cin >> a; // a 是十六進制數
轉換回十進制
要使輸入爲十進制數,首先切換至十進制輸入
cin >> dec;
//接下里就可以輸入十進制數了
cin >> a; // a 是十進制數
最後附加代碼驗證:
// 八進制:
#include<iostream>
#include<iomanip>
using namespace std;
typedef long long ll;
int main()
{
ll a,b;
while(cin>>oct>>a>>b)
{
cout<<oct<<a+b<<endl;
}
return 0;
}
4 6
12
4 7
13
6 7
15
7 7
16
17 16
35
// ps:默認是十進制,十六進制上面已經驗證過了:
【c】
#include <stdio.h>
void main(void)
{
int x;
scanf("%o", &x ); //按8進制輸入
printf("hex:%#X, dec:%d, oct:%#o\n", x,x,x ); //按16進制 10進制 8進制進行數據輸出
}
scanf("%llX",&x)//按十六進制輸入
printf("%llX,x) // 按十六進制輸出
// 對於十進制就不多介紹了
附上實現代碼:
// 八進制
#include<stdio.h>
int main()
{
long long a,b;
while(scanf("%o%o",&a,&b))
{
printf("%o\n",a+b);
}
return 0;
}
7 7
16
7 16
25
7 14
23