文章

2

粉丝

0

获赞

9

访问

986

头像
P1422 进制转换3 答疑提问(Time Limited):
P1422 清华大学/厦门大学机试题
发布于2025年3月20日 10:51
阅读数 538

具体代码如下,想着写一个数组模拟进制转换的万用方法,算法复杂度应该是O(n^2),不理解为什么会导致超时,用于提交其他题目也是能成功通过的,个人初步推断是有特殊情况的用例没有考虑到导致bug才引起的超时,但实在找不到是哪种情况,麻烦大佬们给给意见,谢谢!

#include <stdio.h>  
#include <string.h>  
#include <math.h>  
#include <stdlib.h>  
#include <time.h>  
#include <algorithm>  
#include <iostream>  
#include <queue>  
#include <stack>  
#include <vector>  
#include <string>  
using namespace std; 


char radixForm(int num){    
    return num<10?num+'0':(num-10)+'a';
}

int radixForm(char ch){ 

    if(ch>='a'){
        ch=ch-'a'+'A';
    }
    return ch<='9'?ch-'0':ch-'A'+10;
}

string legalizedNumStr(string s,int radix){

    while(s[0]=='0'&&...

登录查看完整内容


登录后发布评论

3 条评论
快乐小土狗
2025年3月20日 12:00

修改后的代码

#include <iostream>
#include <vector>
#include <string>

using namespace std;

// 将数字转换为对应进制字符
char radixForm(int num) {
    return num < 10 ? num + '0' : (num - 10) + 'a';
}

// 将字符转换为对应数字
int radixForm(char ch) {
    return ch <= '9' ? ch - '0' : ch - 'A' + 10;
}

// 去除字符串开头的0
string legalizedNumStr(const string& s, int radix) {
    int i = 0;
    while (i < s.length() && s[i] == '0') {
        i++;
    }
    string newStr = s.substr(i);
    if (newStr.empty()) {
        newStr = "0";
    }
    for (char ch : newStr) {
        if (radix <= radixForm(ch)) {
            return "0";
        }
    }
    return newStr;
}

// 任意进制转换
string radixConvert(const string& os, int oldRadix, int newRadix) {
    string s = legalizedNumStr(os, oldRadix);
    if (s == "0") {
        return s;
    }
    vector<int> num(s.length());
    for (int i = 0; i < s.length(); i++) {
        num[i] = radixForm(s[i]);
    }
    vector<int> result;
    while (true) {
        int remainder = 0;
        vector<int> quotient;
        for (int i = 0; i < num.size(); i++) {
            int current = remainder * oldRadix + num[i];
            quotient.push_back(current / newRadix);
            remainder = current % newRadix;
        }
        result.push_back(remainder);
        int i = 0;
        while (i < quotient.size() && quotient[i] == 0) {
            i++;
        }
        num.assign(quotient.begin() + i, quotient.end());
        if (num.empty()) {
            break;
        }
    }
    string bs;
    for (int i = result.size() - 1; i >= 0; i--) {
        bs += radixForm(result[i]);
    }
    return bs;
}

int main() {
    int ra1, ra2;
    string a;
    cin >> ra1 >> ra2;
    cin >> a;
    string ans = radixConvert(a, ra1, ra2);
    cout << ans << endl;
    return 0;
}    

 

赞(1)

霞鸣 : 回复 快乐小土狗: 朋友你好,你修改的代码我已经阅读过,raddixConvert函数改成你修改后的代码也能够正常提交了。虽然缩小了问题的排查范围,但我还是有些摸不着头脑。因为在我看来,您与我思路最主要的区别,就是计算过程中朋友你一直用int数组处理,最后才转为string;而我在每一步都进行了二者的互相转换。虽然每次循环我的代码多了2步,但整体算法复杂度依然是O(n^2),为什么会导致如此大的结果差异呢?或者我是疏忽了什么呢?

2025年3月20日 14:15

霞鸣 : 回复 快乐小土狗: 我回头再找找问题,不论如何,朋友你的这段代码已经很有帮助了,十分感谢。

2025年3月20日 14:24