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 值)。通过这种特性,简单的数学运算就可以实现字符和数字的转换。

相关推荐
练习时长一年2 小时前
Leetcode热题100(跳跃游戏 II)
算法·leetcode·游戏
小白菜又菜7 小时前
Leetcode 3432. Count Partitions with Even Sum Difference
算法·leetcode
wuhen_n8 小时前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
sin_hielo8 小时前
leetcode 2483
数据结构·算法·leetcode
Xの哲學9 小时前
Linux多级时间轮:高精度定时器的艺术与科学
linux·服务器·网络·算法·边缘计算
大头流矢9 小时前
归并排序与计数排序详解
数据结构·算法·排序算法
油泼辣子多加9 小时前
【信创】算法开发适配
人工智能·深度学习·算法·机器学习
Aaron158810 小时前
AD9084和Versal RF系列具体应用案例对比分析
嵌入式硬件·算法·fpga开发·硬件架构·硬件工程·信号处理·基带工程
laocooon52385788610 小时前
插入法排序 python
开发语言·python·算法
wuhen_n11 小时前
LeetCode -- 1:两数之和(简单)
javascript·算法·leetcode·职场和发展