「GUETOJ」P1042 孤独的桂电人

题目描述:

一天,xcq和yy想比比谁比较孤独,但孤独这种东西无法量化难以比较,为此,他们想出了一个方法,两人各写一个数字,然后转化为二进制,谁的数字中二进制1多谁就比较孤独

思路:

这个题目的数据范围比较大,所以必须写一个大数除法,但是只用管除以2 ,所以跟一般的大数出发不同,会简单一些。



#include 
#include 
using namespace std;

bool not_zero(char * input);
int divide_2(char*);
int count_1(char*);
int main(void)
{
    char xcq[100];
    char yy[100];
    int ans_xcq=0, ans_yy=0;
    
    scanf("%s",xcq);
    scanf("%s",yy);

    ans_xcq = count_1(xcq);
    ans_yy = count_1(yy);

    if(ans_xcq == ans_yy)
    {
        printf("neither");
    }
    else if(ans_xcq>ans_yy)
    {
        printf("xcq");
    }
    else 
    {
        printf("yy");
    }
}

int divide_2(char * input) //除以2返回余数
{
    int t=0;
    char * p = input;
    while((*p) == '0')  //忽略前面的0
    {
        ++p;
    }
    t = (*p - '0') % 2;
    *p = (*p - '0' - t) / 2 + '0'; //记录第一位数的除法结果
    p += 1;
    while(*p)
    {
        t = t*10 + (*(p) - '0'); //把下一位数放下来
        *p = (t - (t%2)) / 2 + '0';
        t = t % 2;
        p++;
    }

    return t;
}

bool not_zero(char * input) //如果不为零,返回真
{
    for(int i=0; input[i] != '\0'; i++)
    {
        if(input[i] != '0')
        {
            return true;
        }
    }
    return false;
}

int count_1(char * input) //只要记录1的个数就行。返回1的个数
{
    int ans = 0;
    while(not_zero(input))
    {
        if(divide_2(input))
        {
            ++ans;
        }
    }
    return ans;
}


你可能感兴趣的:(GUETOJ,算法)