Test question algorithm training-2 base (C++)

Resource limitation
Time limitation: 1.0s Memory limitation: 256.0MB
Problem description
  Given a decimal integer N, calculate its -2 binary representation.
Input format
  First line: an integer N, representing the decimal number to be converted.
Output format    The
  first line: the -2 hexadecimal representation of N.

Sample input-
13

Sample output
110111

The data size and the agreed
  100% data meet:|n|<=2000000000.
Tips
  negative binary:
  there is such a number 100110, it is a -2 base number, the method to convert it to a decimal number is 1*(-2)5 + 0*(-2)4 + 0*(- 2)3 + 1*(-2)2 + 1*(-2)1 + 0*(-2)0 is equal to -30.

110111 is converted into a negative binary number: 1*(-2)5 + 1*(-2)4 + 0*(-2)3 + 1*(-2)2 + 1*(-2)1 + 1* (-2) 0 is equal to -13

In the -2 base number, the number in each position can only be 0 or 1. It can be proved that every decimal number can be expressed as a -2 base number, and the way of expression is unique.

#include<iostream>
#include<vector>
using namespace std;
vector<int> vec;
int main()
{
    
    
	int n ;
	scanf("%d",&n);
	if(n==0){
    
    
		printf("0\n");
        return 0;
	}
	while(n!=1){
    
    
		if(n%(-2)==0){
    
    
	        n/=(-2);
			vec.push_back(0);
		}else{
    
    
			vec.push_back(1);
			if(n>0){
    
    
				n=n/(-2);	
			}else{
    
    
				n=n/(-2)+1;
			}		
		}
	}
	vec.push_back(1);
	for(int i=vec.size()-1;i>=0;i--){
    
    
		printf("%d",vec[i]);
	}
	printf("\n");
	return 0;
} 

Guess you like

Origin blog.csdn.net/weixin_51430516/article/details/115356792