Created
March 13, 2016 07:35
-
-
Save jianminchen/aba5bad049353738a520 to your computer and use it in GitHub Desktop.
Gem Stones - HackerRank - Julia uses bit manipulation to implement the solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace GemStone3 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string s = Console.ReadLine(); | |
int n = Convert.ToInt16(s); | |
string[] sA = new string[n]; | |
for (int i = 0; i < n; i++) | |
{ | |
sA[i] = Console.ReadLine(); | |
} | |
Console.WriteLine(getNumberOfGemElement(sA)); | |
} | |
/* | |
* string length >=1, <=100 | |
* only lower-cse Latin letters 'a'-'z' | |
* | |
* string array size 1 - 100 | |
* | |
* using bit manipulation to solve the problem - March 12, 2016 | |
* C++ Integer.bitCount C# analog | |
* | |
*/ | |
public static int getNumberOfGemElement(string[] s1) | |
{ | |
int n = s1.Length; | |
int x = -1; // julia, debug the code, and learn the idea to use bit manipulation | |
for(int i = 0;i < n;i++){ | |
char[] s = s1[i].ToCharArray(); | |
int b = 0; | |
foreach(char c in s){ | |
b |= 1 << c-'a'; | |
} | |
x &= b; | |
} | |
return bitCount(x); | |
} | |
/* | |
* C++ Integer.bitCount | |
* Try to look up C# solution - could not find it | |
* So, write one | |
*/ | |
private static int bitCount(int x) | |
{ | |
int count = 0 ; | |
for(int i=0;i<26; i++) | |
{ | |
int b = 1 << i; | |
if ((x & b) >0) // bug001: x & b >0 -> should be: (x & b) >0 | |
count++; | |
} | |
return count; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment