P8723 [蓝桥杯 2020 省 AB3] 乘法表

P8723 [蓝桥杯 2020 省 AB3] 乘法表

cpp 复制代码
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm>
#include <format>
string toBaseP(int  n,int  p){//这里不要取引用,因为会改变值
  if(n == 0) return 0;
  string res = ""; 
  while(n){
    int mod = n %p;
     res += (mod < 0?mod + '0':mod -10 + 'A');
     n /=p;
  }
  reverse(res.begin(),res.end());
  return res;
 
}
int main(){
  int n;
  cin>>n;
  for(int i=1;i<=n-1;i++){
    for(int j =1;j<=i;j++){
      int a = i *j;
      cout<<format("{}*{}={} ",toBaseP(i,n),toBaseP(j,n),toBaseP(a,n));
      /*这里的 n 是通过引用传递的(int &n),意味着在函数内部修改 n 会直接改变调
      用时的实际参数值。这在转换进制的过程中会破坏原始的值,
      导致调用 toBaseP 后 i 和 j 的值被修改。 */
      //cout<<i<<"*"<<j<<"="<<a/n<<a%n<<" ";
    }
  cout<<endl;
  }
}

C++ 中允许将字符和整数直接进行算术运算,这是因为字符在底层被存储为整数(ASCII 值)。通过这种特性,简单的数学运算就可以实现字符和数字的转换。

相关推荐
米粒110 小时前
力扣算法刷题 Day 31 (贪心总结)
算法·leetcode·职场和发展
少许极端10 小时前
算法奇妙屋(四十)-贪心算法学习之路7
java·学习·算法·贪心算法
AlenTech10 小时前
647. 回文子串 - 力扣(LeetCode)
算法·leetcode·职场和发展
py有趣10 小时前
力扣热门100题之合并两个有序链表
算法·leetcode·链表
8Qi811 小时前
LeetCode热题100--45.跳跃游戏 II
java·算法·leetcode·贪心算法·编程
foundbug99911 小时前
基于STM32的步进电机加减速程序设计(梯形加减速算法)
stm32·单片机·算法
北顾笙98011 小时前
day12-数据结构力扣
数据结构·算法·leetcode
凌波粒12 小时前
LeetCode--454.四数相加 II(哈希表)
算法·leetcode·散列表
漫随流水12 小时前
c++编程:D进制的A+B(1022-PAT乙级)
数据结构·c++·算法
tankeven12 小时前
HJ159 没挡住洪水
c++·算法