社区讨论

蒟蒻问个问题

P1143进制转换参与者 3已保存回复 2

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
2 条
当前快照
1 份
快照标识符
@mhj3sa2r
此快照首次捕获于
2025/11/03 20:15
4 个月前
此快照最后确认于
2025/11/03 20:15
4 个月前
查看原帖
这是我的AC代码:
CPP
//洛谷 P1143 进制转换 
#include<bits/stdc++.h>
using namespace std;
//#define LOCAL//
#define emdl '\n'
#define endl '\n'
typedef long long ll;
typedef unsigned long long ull;
const int MAXN=1e5+5;
const ll INF=1e18;

int n,m;
int sum[MAXN]; 

int main(){
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	#ifdef LOCAL
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    #endif
    
    cin>>n;
    string s;
    cin>>s;
    cin>>m;
    
    //n->10 
    int res=0;
    for(int ch:s){
    	if('0'<=ch && ch<='9'){
    		sum[++res]=(ch-'0');
		}
		else{
			sum[++res]=(ch-'A'+10);
		}
	}
	
	//
//	for(int i=1;i<=res;i++) cout<<sum[i]<<" ";
//	cout<<emdl;
	//
	
	int num=0;
	for(int i=1;i<=res;i++){
		num*=n;
		num+=sum[i];
		//cout<<num<<emdl;// 
	}
	
	//10->m
	stack<int> st;
	while(num>0){
		st.push(num%m);
		num/=m; 
	}
	
	while(!st.empty()){
		int fr=st.top();
		st.pop();
		if(fr>=10){
			cout<<(char)(fr-10+'A'); 
		}
		else{
			cout<<fr;
		}
	}
	
	cout<<emdl; 

	return 0;
}
注意到29行的 for(int ch:s){
可能因为我太菜了,我觉得这样是有问题的,应该写成 for(char ch:s){
但是这个代码却AC了。
所以来问一下各位大佬为什么会这样。。。

回复

2 条回复,欢迎继续交流。

正在加载回复...