A negative binary representation of a number, such as 21=1+4+16, when num>21 maximum with 64-32 for 32, otherwise the maximum of 16 can be, when num=31, 31-32=-1, in the transfer to deal with negative function
1 /*0.003s*/2#include <iostream>3#include <cstdio>4#include <cstring>5#include <cmath>6 using namespacestd;7 8 intnum,t,cas=1;9 Charans[ +];Ten One voidNegintnum); A - voidNot_neg (intNum//working with positive numbers - { the Long Longm=1, e=2, n=0; - while(num>m) - { -M= (m<<2)+1;//m=2^0+2^2+...+2^2n +e<<=2;//2^2n+1 -n+=2; + } A while(num>1) at { -m>>=2; e>>=2; - if(num>m+e)//num>2^0+2^2+...+2^2 (n-1) +2^2n-1 with 2^2n - { -ans[n--]='1'; -n--; innum-=e<<1; - } to Else if(num>m)//otherwise with -2^2n-1 + 2^2n + { -ans[n--]='1'; theans[n--]='1'; *num-=e; $ }Panax Notoginseng Elsen-=2; - } the if(num<0) neg (num);//alternating between positive and negative + Else if(num==1) ans[0]='1'; A } the + voidNegintNum//Handling Negative numbers - { $Num=-num;//convert to positive, similar to positive processing $ Long Longm=2, e=4, n=1; - while(num>m) - { theM= (m<<2)+2; -e<<=2;Wuyin+=2; the } - while(num>2) Wu { -m>>=2; e>>=2; About if(num>m+e) $ { -ans[n--]='1'; -n--; -num-=e<<1; A } + Else if(num>m) the { -ans[n--]='1'; $ans[n--]='1'; thenum-=e; the } the Elsen-=2; the } - if(num<0) Not_neg (-num);//alternating between positive and negative in Else if(num==2) ans[1]='1'; the Else if(num==1) ans[0]=ans[1]='1'; the } About intMain () the { thescanf"%d",&T); the while(t--) + { -scanf"%d",&num); theprintf"Case #%d:", cas++);Bayimemset (ans,'0',sizeof(ans));//initialize all characters to ' 0 ', then just set 1 theNum>0?Not_neg (num): Neg (num); the intI= the; - while(ans[i]=='0'&&i>0) i--;//i>0 At least one, all 0 o'clock also meet - /*num=0; the for (int j=0;j<=i;j++) the j&1?num-= (1<<j) * (ans[j]-' 0 '): num+= (1<<j) * (ans[j]-' 0 '); the printf ("num=%d\n", num);//Test the */ - for(; i>=0; i--) the Putchar (Ans[i]); theprintf"\ n"); the }94 return 0; the}
View Code
UVA 11121 Base-2