PAT Basic Level 1022. D进制的A+B (20)

本文介绍了一种解决D进制下两数相加的问题,通过C++和C语言实现,适用于PAT考试等编程竞赛场景。文章提供了详细的代码示例,并解释了如何将十进制结果转换为指定进制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【来源】

1022. D进制的A+B(20)

【分析】

此题考察进制转换的相关知识。

【代码】

#include <iostream>
#include <vector>
using namespace std;

int main()
{
  int a, b;
  cin >> a >> b;
  int d;
  cin >> d;
  int c = a+b;

  if(c == 0){
    cout << 0 << endl;
  }
  else{
  vector<int> digits;
    while(c){
      int digit = c % d;
      c /= d;
      digits.push_back(digit);
    }
    for(int i = digits.size()-1; i >=0; --i){
      cout << digits[i];
    }
    cout << endl;
  }


  return 0;
}
【点评】

此题为PAT2014.3.1春季考试第二题,属于简单题。

【附C语言版】

#include <stdio.h>
int main()
{
    int a, b, c, d;
    scanf("%d%d%d", &a, &b, &d);
    c = a + b;

    if (c == 0){
        printf("0\n");
    }
    else{
        int digits[30];
        int i = 0;
        while (c){
            int digit = c % d;
            c /= d;
            digits[i++] = digit;
        }
        while (i--){
            printf("%d", digits[i]);
        }
        printf("\n");
    }

    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值