ickchen2

PKU3191 求负进制

/*负权进制*/
#include<stdio.h>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<queue>
#include<algorithm>
#define M 1000
using namespace std;
int a[M];
int main()
{
    int n;
    scanf("%d",&n);
    if(n==0){printf("%d\n",n);return 0;}//记得判断0
    int m=n;
    int p=1;
    if(m<0){p=0;m*=-1;}
    int k=0;
    while(m)
    {
        a[k++]=m%2;
        m/=2;
    }
    for(int i=p;i<k;i++)//伪奇指数位取反
    {
        if(((i-p)&1)==0)
        {
            a[i]*=-1;
        }
    }
    int i;
    for(i=0;i<k;i++)
    {
        if(a[i]<0)//负数,进位
        {
            a[i+1]+=(-a[i]/2)+(-a[i]%2&&1);
            a[i]+=((-a[i]/2)+(-a[i]%2&&1))*2;
        }
  else//正数,借位
  {
   a[i+1]-=a[i]/2;
   a[i]%=2;
  }
    }
    while(a[i])
    {
        if(((i-p)&1)==0)
        {
            if(a[i]<0)
   {
                a[i+1]+=(-a[i]/2)+(-a[i]%2&&1);
                a[i]+=((-a[i]/2)+(-a[i]%2&&1))*2;
   }
      else
   {
       a[i+1]-=a[i]/2;
       a[i]%=2;
   }
        }
        else
        {
            if(a[i]<0)
            {
                //a[i]*=-1;
                a[i+1]+=(-a[i]/2)+(-a[i]%2&&1);
                a[i]+=((-a[i]/2)+(-a[i]%2&&1))*2;
            }
   else
   {
    a[i+1]-=a[i]/2;
       a[i]%=2;
   }
        }
  i++;
    }
    for(i-=1;i>=0;i--)
    {
        printf("%d",a[i]);
    }
    printf("\n");
}

posted on 2008-09-11 12:51 神之子 阅读(268) 评论(0)  编辑 收藏 引用 所属分类: ACM题解


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿(1)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜