1022. D進制的A+B (20)
輸入兩個非負10進制整數A和B(<=230-1),輸出A+B的D (1 < D <= 10)進制數。
輸入格式:
輸入在一行中依次給出3個整數A、B和D。
輸出格式:
輸出A+B的D進制數。
輸入樣例:123 456 8輸出樣例:
1103
答案:
#include"stdafx.h"//這行PAT的編譯器是不能識別的,但是VS2017是必要的
#include<stdio.h>
#include<stdlib.h>
int main()
{
int first;
int second;
int third;
int d;
scanf("%d%d%d", &first, &second, &d);
third = first + second;
int a[30];
int number = 0;
while (third>=0)
{
if (third == 0&&number==0)
{
a[number] = third;
number++;
break;
}
if (third == 0 && number > 0)
{
break;
}
a[number] = third %d;
third = third / d;
number++;
}
while (number>0)
{
number--;
printf("%d", a[number]);
}
system("PAUSE");
return 0;
}
下面的簡潔的代碼:
#include<iostream>
using namespace std;
void test(int m,int k){
if(m/k==0)cout<<m;
else{
test(m/k,k);
cout<<m%k;}
}
int main(){
int A,B,D;
cin>>A>>B>>D;
int cnt=0;
cnt=A+B;
test(cnt,D);
system("pause");
return 0;
}