Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 4, 2016 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/bcf7ade62dc35a85993b102c40584abe to your computer and use it in GitHub Desktop.
Save jianminchen/bcf7ade62dc35a85993b102c40584abe to your computer and use it in GitHub Desktop.
AorB - HackerRank C# - study code #6 - BigInteger - try the class yourself
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
class Solution
{
static void Main(String[] args)
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
byte[] lookup = new byte[256];
for (int i = 0; i < lookup.Length; i++)
{
byte sum = 0;
int temp = i;
while (temp > 0)
{
sum += (byte)(temp % 2);
temp >>= 1;
}
lookup[i] = sum;
}
int t = Convert.ToInt32(Console.ReadLine());
for (int a0 = 0; a0 < t; a0++)
{
int k = Convert.ToInt32(Console.ReadLine());
BigInteger A = ReadHex();
BigInteger B = ReadHex();
BigInteger C = ReadHex();
BigInteger A2 = A & C;
BigInteger A3 = A2 ^ A;
BigInteger B2 = B & C;
BigInteger B3 = B2 ^ B;
BigInteger C2 = ((C ^ A2) | B2) ^ B2;
foreach (byte b in A3.ToByteArray())
{
k -= lookup[b];
}
foreach (byte b in B3.ToByteArray())
{
k -= lookup[b];
}
foreach (byte b in C2.ToByteArray())
{
k -= lookup[b];
}
if (k < 0)
Console.WriteLine(-1);
else
{
A2 = A - A3;
B2 = B - B3 + C2;
C2 = A2 & B2;
byte[] Ab = A2.ToByteArray();
byte[] Bb = B2.ToByteArray();
byte[] Ra, Rb;
byte[] bit = { 128, 64, 32, 16, 8, 4, 2, 1 };
if (Ab.Length > Bb.Length)
{
Ra = Ab;
Rb = new byte[Ab.Length];
Array.Copy(Bb, 0, Rb, 0, Bb.Length);
}
else
{
Rb = Bb;
Ra = new byte[Bb.Length];
Array.Copy(Ab, 0, Ra, 0, Ab.Length);
}
for (int i = Ra.Length - 1; i >= 0; i--)
{
for (int j = 0; j < 8; j++)
{
if (k == 0)
break;
if ((Ra[i] & bit[j]) == 0)
{
continue;
}
else if ((Ra[i] & bit[j]) == (Rb[i] & bit[j]))
{
Ra[i] -= bit[j];
k--;
}
else if ((Ra[i] & bit[j]) == bit[j]
&& (Rb[i] & bit[j]) == 0
&& k > 1)
{
Ra[i] -= bit[j];
Rb[i] += bit[j];
k -= 2;
}
}
if (k == 0)
break;
}
PrintHex(Ra);
PrintHex(Rb);
}
}
}
static void PrintHex(byte[] s)
{
bool firstDigit = true;
for (int i = s.Length-1; i >= 0; i--)
{
if (s[i] == 0 && firstDigit)
continue;
string s2 = Convert.ToString(s[i], 16).ToUpper();
if (s2.Length == 1 && !firstDigit)
s2 = "0" + s2;
firstDigit = false;
Console.Write(s2);
}
if (firstDigit)
Console.Write("0");
Console.WriteLine();
}
static BigInteger ReadHex()
{
string S = Console.ReadLine();
if(S.Length % 2 == 1)
{
S = "0" + S;
}
else
{
S = "00" + S;
}
char[] T = S.ToCharArray();
byte[] B = new byte[T.Length / 2];
for (int i = 0; i < T.Length; i += 2)
{
B[B.Length - i / 2 - 1] = Convert.ToByte(T[i] + "" + T[i + 1], 16);
}
return new BigInteger(B);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment