异类异或算法题

/**
 * Created by mahaixu on 2020/3/26.
 */

import java.util.Scanner;

/**
 * @author Create By mahaixu
 * @date 2020/03/26 9:09
 */

public class XOR {


    public static  String opxor(int n , int number){
        String result = "";
        int jinzhi = n+1;
        int shang = number;
        int yushu;

        while(shang > 0 ){
            yushu = shang%jinzhi;
            shang = shang/jinzhi;

            if(yushu > 9){
                result = (char)('a' + (yushu-10)) + result;
            }else{
                result = yushu + result;
            }
        }
        return result;
    }


    public static String aopb(String a, String b, int jinzhi){

        int alength = a.length();
        int blength = b.length();


        String apre = a.substring(0, alength-blength);
        String atail = a.substring(alength-blength, alength);
        String result = apre;

        for (int i = 0 ; i< blength; i++){

            if(atail.charAt(i) + b.charAt(i) > jinzhi){
                result = result + (atail.charAt(i) + b.charAt(i) - jinzhi);
            }else {
                result += (atail.charAt(i) + b.charAt(i));
            }
        }
        return result;

    }


    public static int  turnResult(String result,int jinzhi){

        int d;           // 保存取出的最低位
        int p = 0;      // 保存当前位权,从个位开始
        int sub = 0;    // 保存当前数值
        char c;
        int length = result.length();
        for(int i= 0; i<length;i++) {
            c = result.charAt(i);

            // 将字符转换为对应的数字
            if (c >= 'A' && c <= 'Z') {
                d = c - 55;
            } else if (c >= 'a' && c <= 'z') {
                d = c - 87;
            } else {
                d = c - 48;
            }

            // 当前位权
            p = length - 1 - i;

            // 0^0 = 1
            if (d != 0) {
                sub += d * (int) Math.pow(jinzhi, p);
            }
        }
        // System.out.println("当前位权:"+p+"当前数值:"+d);
        return sub;
    }



    public static void main(String [] args){
        Scanner inn = new Scanner(System.in);
        int n = inn.nextInt();
        Scanner ina = new Scanner(System.in);
        Scanner inb = new Scanner(System.in);
        int a = ina.nextInt();
        int b = inb.nextInt();

        String astr = opxor(a, n);
        String bstr = opxor(b, n);
        if(astr.length() > bstr.length()){
            String result = aopb(astr, bstr, n);
            int r = turnResult(result, n);
            System.out.println(r);
        }else{
            String result = aopb(bstr, astr, n);
            int r = turnResult(result, n);
            System.out.println(r);
        }

    }


}

以上代码仅供参考,可能会有问题,发现的同志请指正

发布了22 篇原创文章 · 获赞 1361 · 访问量 237万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 代码科技 设计师: Amelia_0503

分享到微信朋友圈

×

扫一扫,手机浏览