異類異或算法題

/**
 * 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);
        }

    }


}

以上代碼僅供參考,可能會有問題,發現的同志請指正

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章