HDU 5050 Divided Land 2014 ACM/ICPC Asia Regional Shanghai Online

求2个二进制数的GCD

java大数+位压

import java.math.*;
import java.util.*;
import java.io.*;

public class Main {
    public BigInteger GCD(BigInteger x, BigInteger y) {
        if(x.compareTo(y) < 0) {
            BigInteger tmp = x;
            x = y;
            y = tmp;
        }
        while(y.compareTo(BigInteger.ZERO) != 0) {
            BigInteger tmp = x.mod(y);
            x = y;
            y = tmp;
        }
        return x;
    }
    public void work() {
        int T, cas = 0;
        String a = new String();
        String b = new String();
        char c[] = new char[1005];
        T = cin.nextInt();
        while (T-- > 0) {
            a = cin.next();
            b = cin.next();
            BigInteger x = BigInteger.ZERO;
            for(int i = 0; i < a.length(); i ++) {
                x = x.multiply(BigInteger.valueOf(2));
                if(a.charAt(i) == '1') x = x.add(BigInteger.ONE);
            }
            
            BigInteger y = BigInteger.ZERO;
            for(int i = 0; i < b.length(); i ++) {
                y = y.multiply(BigInteger.valueOf(2));
                if(b.charAt(i) == '1') y = y.add(BigInteger.ONE);
            }
    //        System.out.println(x + "," + y);
            x = GCD(x, y);
            int i = 0;
            while(x.compareTo(BigInteger.ZERO) > 0) {
                if( x.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ZERO) == 0) {
                    c[i] = '0';
                } else c[i] = '1';
                i ++;
                x = x.divide(BigInteger.valueOf(2));
            }
            
            cas ++;
            System.out.print("Case #" + cas + ": ");
            while(i > 0) {
                System.out.print(c[i-1]);
                i--;
            } 
            System.out.println();
        }
    }

    Main() {
        cin = new Scanner(System.in);
    }

    public static void main(String[] args) {
        Main e = new Main();
        e.work();
    }

    public Scanner cin;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值