HzuHtx


私信TA

用户名:hetangxin123

访问量:41197

签 名:

私はいつまでもレムが好きです。

等  级
排  名 29
经  验 14162
参赛次数 10
文章发表 76
年  龄 0
在职情况 学生
学  校 贺州学院
专  业 软件工程

  自我简介:

写不动,根本写不动

解题思路:

            负数的短除其实和正数的短除是一样的.


                    区别只在于,负数短除后可能出现余为负的情况,而进制数中数位是不为负的.


                        解决这个,其实很简单,只要把它变正就好,例子如下.


                            如果要求-7的-2进制数,那么第一步就要用-7来除以-2,商是3,余数是-1.

                            那么余数为负,不符题意,我们就试着改变商,试余数变正,实际上只要把商+1即可,

                            因为余数绝对值恒小于除数的绝对值.
                            也就是说,现在-7除以-2,商变成了4,余数变成了1,

                            以此类推,-7的-2进制数就可以推出是 1001 .
                            对于-13也可这样转换.


        总之一句话:保证余数非负!


        附上代码o(* ̄︶ ̄*)o


#include<stdio.h>
#include<iostream>
#include<string>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
int main()
{
	int n;
	cin >> n;
	if (n == 0)                    //如果为0则输出0
		cout << "0" << endl;
	int k = 0;
	int ans[1001];
	while (n != 0)
	{
		int num = n % (-2);
		if (num < 0)        //如果小于1则商加1,余数变为1
		{
			num = num-(-2);
			n = n / (-2) + 1;
		}
		else
			n = n / -2;
		ans[k++] = num;
	}
	for (int i = k-1; i >= 0; i--)
		cout << ans[i];
	return 0;
}


另外写了个十进制转-N进制的

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <set>
#include <queue>
#include <stack>
using namespace std;
int ans[1001];
int main()
{
	int num, temp;
	cin >> num >> temp;
	int n = num;
	int k = 0;
	while (n != 0)
	{
		int x = n % temp;
		n = n / temp;
		if (x < 0)
		{
			x = x - temp;
			n = n + 1;
		}
		ans[k++] = x;
	}
	printf("%d=", num);
	for (int i = k - 1; i >= 0; i--)
	{
		if (ans[i] > 9)
		{
			char c = ans[i] - 10 + 'A';
			cout << c;
		}
		else
			cout << ans[i];
	}
	printf("(base%d)", temp);
	cout << endl;
	return 0;
}


 

0.0分

1 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区