十进制转为N进制
昨天笔试遇到的题,如果是正数,不断以余数做除法即可:
void convert(int num, int N, vector<char>& data) { int number = num; //if (num < 0) // num = -num; while (num != 0) { int temp = num%N; if (temp <= 9) data.push_back(temp + '0'); else data.push_back(temp - 10 + 'A'); num /= N; } //if (number < 0) // data.push_back('-'); } int main() { int num, N; while (cin >> num >> N) { if (N == 10) { cout << num << endl; continue; } vector<char> data; convert(num, N, data); for (int i = data.size() - 1; i >= 0; i--) { cout << data[i]; } cout << endl; } return 0; }
如果是负数怎么办呢?