P1017 [NOIP2000 提高组] 进制转换(C++/Java)

本题是我刷洛谷题的开篇,主要针对洛谷 普及/提高组 的题目,写博客的目的也是希望在提高自己能力的同时,能够分享给大家一些思路。能力有限,不对的地方还请大家批评指正。

本题传送门:P1017 进制转换
负进制数与正进制数的转换大同小异,都是除以基数再倒取余数就可以,但是负进制转换的过程中,取余时可能会出现负数,这是我们就需要将负余数转换成正数。方法为:将得到的负余数mod + 要转换的进制R,即mod+|R|,这样就使其变成了正数。

C++代码:

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

/**
 * 设 n / R = t ... mod
 * 若 mod < 0, 则 mod + |R| -> mod - R
 * 此时 n = t * R + mod - R + R -> n = (t + 1) * R - R,这样就使负余数变正了
 */
int n, R, temp;
int i = 0;
char ans[1100] = "\0";
const char num[20] = {
    
    '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J'};

int main()
{
    
    
	scanf("%d %d", &n, &R);
	temp = n;

	while (n != 0)
	{
    
    
		int mod = n % R;
		int t = n / R;
		if (mod < 0)
		{
    
    
			mod -= R;
			t++;
		}
		n = t;
		ans[i++] = num[mod];
	}
	
	printf("%d=", temp);
	for (int j = i - 1; j >= 0; j--)
	{
    
    
		printf("%c", ans[j]);
	}
	printf("(base%d)", R);
	return 0;
}

Java代码:

import java.util.Scanner;

public class P1017 {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        final char[] num = {
    
    '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J'};
        char[] ans = new char[1000];
        int temp, i = 0;
        int n = sc.nextInt();
        int R = sc.nextInt();
        temp = n;

        while (n != 0) {
    
    
            int mod = n % R;
            int t = n / R;
            if (mod < 0) {
    
    
                mod -= R;
                t++;
            }
            n = t;
            ans[i++] = num[mod];
        }

        System.out.print(temp + "=");
        for (int j = i - 1; j >= 0; j--)
            System.out.print(ans[j]);
        System.out.print("(base" + R + ")");
    }
}

猜你喜欢

转载自blog.csdn.net/m0_51276753/article/details/121938846