LintCode练习-2824 · 加密的情书-Java-大整数进制转换及异或运算
虽然用Java语言中的BigInteger可以直接对大数进行操作,但如果不是Java,是C/C++之流呢?
所以用Java语言写了一个进制转换及运算的代码。
1 import org.jetbrains.annotations.NotNull; 2 3 import java.math.BigInteger; 4 import java.util.Arrays; 5 import java.util.Scanner; 6 7 import static java.lang.System.*; 8 9 public class Main { 10 public static void main(String[] args) { 11 Scanner scanner = new Scanner(System.in); 12 String xxx = scanner.next(); 13 int[] inV = new int[xxx.length()]; 14 for (int i = 0;i<xxx.length();i++) 15 inV[i] = xxx.charAt(i) - '0'; 16 int[] invs = {1,9,9,9,0,6,0,6}; 17 int[] plaintext = decimalToBinary(inV,10,2); // 十进制转二进制 18 int[] seckey = decimalToBinary(invs, 10,2); 19 int[] encrytext = myXOR(plaintext,seckey); // 两个二进制异或运算 20 int[] binaryencry = decimalToBinary(encrytext,2,10); // 二进制转十进制 21 for (int i = 0; i < binaryencry.length; i++) 22 System.out.print(binaryencry[i]); 23 /** 24 * Java调包简单实现大整数运算 25 * BigInteger inputn = new BigInteger(xxx); 26 * BigInteger seckey = BigInteger.valueOf(19990606); 27 * System.out.print(inputn.xor(seckey)); 28 */ 29 } 30 public static int[] myXOR(int[] inA, int[] inB) { 31 int lenMax, lenMin; 32 int[] inMax, inMin; 33 if (inA.length > inB.length){ 34 lenMax = inA.length; 35 lenMin = inB.length; 36 inMax = inA; 37 inMin = inB; 38 }else { 39 lenMax = inB.length; 40 lenMin = inA.length; 41 inMax = inB; 42 inMin = inA; 43 } 44 int[] outC = new int[lenMax]; 45 int index1 = -1; 46 for (int i = 0; i < lenMax-lenMin; i++) { 47 outC[i] = inMax[i] == 0 ? 0 : 1; 48 if (index1 == -1 && outC[i] == 1) 49 index1 = i; 50 } 51 for (int i = lenMax - lenMin, j = 0; i < lenMax; i++, j++){ 52 outC[i] = inMax[i] == inMin[j] ? 0 : 1; 53 if (index1 == -1 && outC[i] == 1) 54 index1 = i; 55 } 56 int k = 0; 57 if (index1 == -1) 58 return outC; 59 int[] outV = new int[lenMax-index1]; 60 for (int i = index1; i < lenMax; i++) 61 outV[k++] = outC[i]; 62 return outV; 63 } 64 public static int[] decimalToBinary(@NotNull int[] inValue, int oldBase, int newBase){ 65 // 十进制转二进制-对商求余 存储余数及更新原被除数 66 int[] out = new int[1000000]; 67 int len = inValue.length; 68 int j, k= 0; 69 int shangs = 1; 70 while (shangs != 0){ 71 shangs = 0; 72 for(int i = 0;i < len; i++){ 73 j = i + 1; 74 int shang = inValue[i] / newBase; 75 int yu = inValue[i] % newBase; 76 if (i==(len-1)) 77 out[k++] = yu; 78 else 79 inValue[j] += yu*oldBase; 80 inValue[i] = shang; 81 shangs += shang; 82 } 83 } 84 int outRe[] = new int[k]; 85 for(int i = 0;i < k;i++) 86 outRe[i] = out[k-i-1]; 87 return outRe; 88 } 89 90 }