Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 4, 2016 00:01
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/1a8344f1fd0729dfc9e3e3e9be98d303 to your computer and use it in GitHub Desktop.
Save jianminchen/1a8344f1fd0729dfc9e3e3e9be98d303 to your computer and use it in GitHub Desktop.
AorB HackerRank C sharp - study code #5 - BitArray
using System;
using System.Text;
using System.Collections.Generic;
using System.Collections;
using System.IO;
using System.Globalization;
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 */
int Q = Int32.Parse(System.Console.ReadLine());
for (int j = 0; j < Q; j++)
{
int K = Int32.Parse(System.Console.ReadLine());
BitArray A1 = ConvertHexToBitArray(System.Console.ReadLine());
BitArray B1 = ConvertHexToBitArray(System.Console.ReadLine());
BitArray C1 = ConvertHexToBitArray(System.Console.ReadLine());
int m = Math.Max(Math.Max(A1.Count, B1.Count), C1.Count);
BitArray A = new BitArray(m);
for(int i = 0; i < A1.Count; i++)
A[A.Count-i-1] = A1[A1.Count -i -1];
BitArray B = new BitArray(m);
for(int i = 0; i < B1.Count; i++)
B[B.Count-i-1] = B1[B1.Count -i-1];
BitArray C = new BitArray(m);
for(int i = 0; i < C1.Count; i++)
C[C.Count-i-1] = C1[C1.Count -i-1];
for (int i = 0; i < m; i++)
{
if (C[i])
{
if (!A[i] && !B[i])
{
B[i] = true;
K--;
}
}
if (!C[i])
{
if (A[i])
{
A[i] = false;
K--;
}
if (B[i])
{
B[i] = false;
K--;
}
}
}
if (K > 0)
{
for (int i = 0; i < m; i++)
{
if (C[i])
{
if (A[i])
{
if (B[i])
{
if (K > 0)
{
A[i] = false;
K--;
}
}
if (!B[i])
{
if (K >= 2)
{
A[i] = false;
B[i] = true;
K = K - 2;
}
}
}
}
}
}
if (K < 0)
System.Console.WriteLine(-1);
if (K >= 0)
{
System.Console.WriteLine(ConvertBitArrayToHex(A));
System.Console.WriteLine(ConvertBitArrayToHex(B));
}
}
}
public static BitArray ConvertHexToBitArray(string hexData)
{
if (hexData == null)
return null; // or do something else, throw, ...
BitArray ba = new BitArray(4 * hexData.Length);
for (int i = 0; i < hexData.Length; i++)
{
int h = Int32.Parse(hexData[i].ToString(), System.Globalization.NumberStyles.HexNumber);
for (int j = 0; j < 4; j++)
{
ba.Set(i * 4 + (3-j), (h & (1 << j)) != 0);
}
}
return ba;
}
public static string ConvertBitArrayToHex(BitArray ba)
{
if (ba == null)
return null; // or do something else, throw, ...
StringBuilder s = new StringBuilder(ba.Length);
for (int i = 0; i < ba.Length; i=i+4)
{
s.Append((8*Convert.ToInt32(ba[i])+4*Convert.ToInt32(ba[i+1])+2*Convert.ToInt32(ba[i+2])+1*Convert.ToInt32(ba[i+3])).ToString("X"));
}
string ss = s.ToString();
ss = ss.TrimStart('0');
if( ss == "") ss = "0";
return ss;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment