# Technical Interview Questions

interview questions shared by candidates

## Technical Interview Questions

### Front End Web Developer at LinkedIn was asked...

If we wanted to implement a method of tracking every click that the user made on the site, how would we want to do this? 1 AnswerPlace a JavaScript event listener for all clicks at the document level. Perform actions based on the details of the click. This problem had multiple branches and sub-questions, but the gist is that you would want to capture the events as they bubbled back up to the document level. There are other acceptable answers to this question. |

### Housekeeper at Wyndham Destinations was asked...

How many rooms at your old job did you clean. 1 AnswerAround 1 every half hour |

### Maintenance Technician at Tesla was asked...

I was asked to describe what is a router, like the one used in the home for the internet. 1 AnswerSwitches create a network. Routers connect networks. A router links computers to the Internet, so users can share the connection. A router acts as a dispatcher, choosing the best path for information to travel so it's received quickly. |

Why does one use MSE as a measure of quality. What is the scientific/mathematical reason for the same? 2 AnswersMean-Square error is an error metric for measuring image or video quality it is popular video and image quality metric because the analysis and mathematics is easier with this L2-Norm metric. Most video and image quality experts will agree that MSE is not a very good measure of perceptual video and image quality. The mathematical reasoning behind the MSE is as follows: For any real applications, noise in the readings or the labels is inevitable. We generally assume this noise follows Gaussian distribution and this holds perfectly well for most of the real applications. Considering 'e' follows gaussian distribution in y=f(x) + e and calculating the MLE, we get MSE which is also L2 distance. Note: Assuming some other noise distribution may lead to other MLE estimate which will not be MSE. |

### Sales Strat Intern at Goldman Sachs was asked...

Suppose we hire you, and you and the rest of the new interns decide to go buy a cup of coffee. Each intern purchases one cup of coffee. One of the interns suggests everyone play a game. Everyone will flip a fair coin, dividing the group of interns into two subgroups: those that got heads and those that got tails. The game is this: whichever group is smaller evenly splits the cost of everyone's cup of coffee (i.e. if there are 5 interns, 3 get H, 2 get T, then the two interns that got tails each buy 2.5 cups of coffee). However, nothing says you need to play this game. You can choose to buy your own cup of coffee and not play the game at all. The question: Should you play this game? (Note: You may assume that there is an odd number of interns, so there are no ties, and that if everyone gets H or everyone gets T, then everyone loses and just buys their own cup of coffee). 18 AnswersHint: Despite its look, this is not a math question. I dont get it, Would you please provide more hints? Assume each coffee costs $1, for simplicity. So this is effectively a choice between two outcomes: paying $1 with probability 100%, or paying $0 with some probability and paying more than $0 with some probability. So you ask yourself: what is your expected cost in the second case? Give that a try and see if you can figure it out. However, I want to remind you that the question is "should you play this game?" The answer to this question isn't just a math question. If you only work out expected values, you've missed the point. For example, a separate question (with the same kind of flavor as the direction I'm trying to lead you) is this: suppose I give you a choice of two outcomes. Either you get $1 with 100% probability or I give you $500,000,000 with probability 1/100,000,000 and 0 otherwise. Which would you pick? Now what if it was the same first choice, but the second choice was $50 with prob 1/10 and 0 otherwise? Now which would you pick? These are the kinds of things you want to think about while answering this kind of question. Let me know if you have anymore questions. And if you want me to post the answer, just let me know. Show More Responses I think I get it. It's about investor's risk appetite. Investors is likely to take guaranteed gains, here is $1. Well yes and no. This is indeed a risk aversion question. If you work it out, you'll find that the EV in each case is exactly the same (your EV is -1 cup of coffee in both scenarios) but that's not the end of it. It's also really a question for them to test your risk aversion. You can really support either answer, and *should* comment on the validity of either answer. My answer was to go with buying my own cup of coffee, and followed it up with a story where a friend of mine had tried to get us to play credit card roulette (which is similar in spirit to this game) and I told him that I did, in fact, say no in that instance and why I said no. However, traditionally people are risk-averse when faced with gains and risk-seeking when faced with losses, so many would probably choose to play the game. But this is as much a question about your psychology as it is about your math skills. And that's why this is such an awesome question, and is probably a question that kills most people they ask it to. Would you please explain to me how do you get -1 for the second scenario? There are 50% H and 50% T. Therefore players have 50% opportunity in the winning group. Given 5 interns, there are two combination of lossing group (4 vs. 1 and 3 vs. 2). EV=0.5*0 + 0.5*(0.5*-5 + 0.5*-2.5) = -1.875. The probability of winning isn't 50%. It's actually slightly above 50%, but that's not the way to look at it. The total number of coffees that need to be bought is n, where n is the number of interns. Going into this game, every intern is the same so they each have the same expected value, and the sum of the expected values must equal -n. So everyone has an EV of -1 as claimed. Thank you very much. I finally got it. I'm still not sure why you said no if the EV is the same? It's a matter of risk preference. See the example I gave in my Mar 19 posting: "Suppose I give you a choice of two outcomes. Either you get $1 with 100% probability or I give you $500,000,000 with probability 1/100,000,000 and 0 otherwise. Which would you pick? Now what if it was the same first choice, but the second choice was $50 with prob 1/10 and 0 otherwise? Now which would you pick? These are the kinds of things you want to think about while answering this kind of question." You would probably not play in the first instance and consider possibly playing in the second. (And those instances even have the risky game with a HIGHER EV). This coffee game is the same kind of game, and even if the EV is the same in each case, the volatility is not the same. It is usually a good rule of thumb to take the lower volatility outcome if the EV is the same (think Sharpe Ratio here! Or think efficient frontier here! Both get the point across I think.). Does that help? I say yes. To play the game. Only because I'm prepared if I lost. The fact that I can afford to loose, makes me want to try my chance at wining I would play the game. Consider the expected price with n total interns splitting a total cost of P. That is P/2*E[1/(N)|you're paying]. This is simply equal to P/2*E[1/(N+1)] where n is a binomial now corresponding to n-1 interns. Notice that 1/n+1 is a concave function. That means that P/2*E[1/(N+1)] <= P/2*(1/E[N]+1)=P/2 * 1/( (n-1)/2 + 1)) = P / (n +1). So it pays to play on average Apologies, but both of the above answers are incorrect. The EV of playing is the same as the EV of not playing. Show More Responses No way would I play! The most money I save is a dollar the most money I can lose ( in the case of five interns) is 4 dollars... That's a 400 percent downside verse a 100 percent upside ( kind of you cannot technically compute your return on zero dollars invested). Plus, I do not even drink coffee! Stupid...I don't have time to play games at work. The EV in both scenarios are not the same: it's clear when think about the case where there are n = 3 interns. I've already explains why they are the same. In either scenario there will be n cups of coffee bought (3 in your case) so total EV is -n (-3 in your case). In the game each person is the same as any other so their EV must all be the same. That is why in the game the EV is -1 (same as if they buy their own cup of coffee). To argue otherwise is to argue that either the total EV is not the number of coffees purchased or that someone has an unfair advantage in the game. Incidentally, if you are going to claim that someone who has given you the answer is wrong, you should provide more of a response than "go think about it." if v = pay by game -1 . Then all have five intern have same distributed V by symmetry 5EV=0 It's zero sum. |

### Software Engineer at Dropbox was asked...

Given an array of integers eg [1,2,-3,1] find whether there is a sub-sequence that sums to 0 and return it (eg 1,2,-3 or 2,-3,1) Checking every sub-sequence is O(n^2) which is too inefficient 14 AnswersShould do a running sum, storing previous sum values in a hash table along with array index if you ever get a sum value you’ve already seen, return the array indices (1+the index in the hash table, and the current index) This solution is O(n) Although the above algorithm runs in O(N) time, will it cover all cases? What about if the input array is [1,2,1,-3,-4]? In this case, the subsequence would be [2,1,-3]. I feel though that the algorithm described above will miss this subsequence since you are only keeping a running sum from the start of the array. Do you mean a subsequence (can be discontinue) or a sub array (continue)? Show More Responses Yes, the solution by Interview Candidate (do a running sum and return when you see a sum already seen) works for all cases. If the list is [1, 2, 1, -3, -4], S1 = 1; S2 = 3 (1 + 2); S3 = 4 (1 + 2 + 1) S4 = 1 (1 + 2 + 1 -3) ... since we have already seen this sum at index 1. the answer is list of numbers at [old_sums_index + 1, new_sums_index] = [2, 1, -3] [100 7 1 2 -3] the above method will not work for this array, It will work for [100 7 1 2 -3]. Index: 0, Sum = 100 (put in hashtable) Index: 1, Sum = 100 + 7 = 107 (put in hashtable) Index: 2, Sum = 107 + 1 = 108 (put in hashtable) Index: 3, Sum = 108 + 2 = 110 (put in hashtable) Index: 4, Sum = 110 + (-3) = 107 107 already exists in hashtable with index = 1. Hence we return (1+1, current index) meaning (2, 4) Doesn't work for [-1,-1,-3,4]. This looks like a classical NP-complete problem: http://en.wikipedia.org/wiki/Subset_sum_problem. And generating all sub sequences is not O(n^2) but O(n!) which is the cost to generate all permutations. It works for [-1 -1 -3 4] too. The subset sum problem allows discontinuous subsets, but this question asks for a subsequence implying no discontinuity. Here is a solution using Python 3: def findZeroSequence(list): hash = {} sum = 0 startIndex = -1 hash[sum] = startIndex # a sum of zero later in the list means the sequence starts at index 0 (== -1 + 1) for i, v in enumerate(list): sum = sum + v # print(i, ' has sum ', sum) try: startIndex = hash[sum] return list[startIndex+1:i+1] except KeyError: hash[sum] = i return [] # no subsequence print(findZeroSequence([1,2,-3,1])) print(findZeroSequence([1,2,1,-3,-4])) print(findZeroSequence([-1,-1,-3,4])) print(findZeroSequence([100, 7, 1, 2, -3])) print(findZeroSequence([-7, -3, -2, 5, 8])) Checking every sub-sequence is O(2^n) not O(n!), which is the cost for generating all subsets. Contrary to what the previous poster said, sub-sequence implies both continuity and discontinuity: http://en.wikipedia.org/wiki/Subsequence and the algorithm fails for this case: [2, 2, 1, -4]. How about these: [1,2,-3,4] or [-3,3,1] ? May be user should check for zero also? def hasSubSeqOfZero(a): if not a: return [] partialSums = {} partSum = 0 for i in range(len(a)): partSum += a[i] if (partSum in partialSums): return a[partialSums[partSum] + 1: i + 1] if (partSum == 0): return a[:i+1] partialSums[partSum] = i return [] Show More Responses public int[] ssz(int[] nums) { if (nums == null || nums.length == 0) return null; Map map = new HashMap(); int sum = 0; int index = 0; for (int n : nums) { if (n == 0) return new int[] { index, index }; sum += n; if (map.containsKey(sum)) { return new int[] { map.get(sum) + 1, index }; } map.put(sum, index); index++; } return null; } |

### Shipping Manifest Clerk at Amazon was asked...

If you saw someone steal a quarter. Would you report it? 10 Answersyes No. I'd talk them out of it. Pay them a quarter from my own pocket if I had to. Who's integrity is worth 25¢? Easy to steal quarters? Where can I get in on this action? Show More Responses It is all part of a yes/no integrity test. The answer is "YES" because they want to know that you think ANY theft is wrong. It depends, if I saw a customer at Walmart reach into the til when the cashier is not looking, I would turn the person in. If my best friend stole a quarter from me, I would not turn her in. What is this?......the plot of Office Space where the guys use a computer program to steal pennies off of each transaction the company makes and then end up getting really rich??? I say if it's just one quarter, it's not worth it. Most stores don't prosecute for petty theft of even $50 or $100. It's not worth your energy. Coming from retail management and knowing how LP is looking at this: It starts with a quarter and usually gets bigger from there. (Greed ) I believe the only right answer is YES its stealing If you are willing to may exception because of the amount it shows that you will bend rules and fail the question. I have worked before companies that fired people for consuming discarded merchandise(written out of inventory like an open package of such-and-such) because it was a policy. Most comanies want to know their policies will be followed to the letter because that helps product the company. Although some companies may bend their rules where they see fit that is not what the interview is about . steal a little steal big, there's only one word to it. thief. steal a little steal big, there's only one word to it. thief. I will report it. Short answer - Yes/No. Deal with it YES. Report it, depends on the circumstances and outcome of my attempt to deal with it. Consider: If I saw someone pocket a quarter from the cash register or steal a small product ($.25 worth) I would definitely report it, but I'd give them the chance to report themselves first. Kind of like my parents would handle it with me, and how I handle it with my children - you steal, you return the merchandise AND pay for it AND apologize. If that doesn't settle the matter we proceed from there. Compared to ... If I saw someone pocket a quarter left on the lunch table at work after a few people got up I would not 'report' that, but would certainly handle it the same as above i.e., make sure they gave the $ (any amount) to one of the people who was sitting there. In Florida this is embraced by a grocery chain called Publix. They call it the Publix Price Guarantee - if they accidentally error on your checkout and you point it out to them they give you a refund for the item AND the item (free). Sorry for the long-winded response, but some of these 'behavioral' questions simply taunt us to relinquish personal &/or social responsibility in the name of 'proper procedure'. If we don't take responsibility for seemingly 'little things' we are in no position to 'blame' anyone when big things go wrong. Kind of like if something bad was happening in the workplace. If I feel it's unsafe to the point I need to leave I will certainly let my manager (and certain other people) know before departing. I think this perspective was forged by a combination of personality and experience. I had the opportunity to visit the WTC on 2/26/1993 for my company after the bombing, so all my co-workers and friends know there comes a time when YOU MUST DECIDE if you stay or if you leave. Restating the point, there comes a time when YOU MUST DECIDE to speak up &/or take action about improper (or illegal) behavior - at the workplace or anywhere else. Happy Holidays all. |

Implement a power function to raise a double to an int power, including negative powers. 11 AnswersCould be implemented many ways. I got the feeling that the interviewer wanted to see you approach the problem in multiple ways and demonstrate confidence in your math and recursive skills. #include #include #define MAX_ARRAY_LENGTH 256 double power(double, unsigned int); int main(int argc, char** argv) { double a = atof(argv[1]); int b = atoi(argv[2]); double result = power(a, b >> 31 == 0 ? b : -b); if ((unsigned int) b >> 31 == 1) { result = 1 / result; } printf("%f\n", result); return 0; } double power(double a, unsigned int b) { switch (b) { case 0: return 1.0; case 1: return a; default: return (b & 1) == 0 ? power(a * a, b >> 1) : power(a * a, b >> 1) * a; } } c implementation of the above (no recursion): int ipow(int base, int exp){ int result = 1; while(exp){ if(exp & 1) { result *= exp; } exp >>= 1; base *= base; } return result; } Show More Responses int power(double n, int exp) { bool npower = (exp < 0) ? true : false; double result = 1; exp = abs(exp); // get the absolute value for (int i = 0; i < exp; i++) { if (npower) { result = result/n; } else { result = result*n; } } return result; } C# code verified: static double Power(double d, int exp) { if (d == 0 || exp == 0) { if (exp >= 0) { return 1; } else { return double.PositiveInfinity; } } int expAbs = Math.Abs(exp); double res = d; for (int i = 1; i 0) ? (res) : (1 / res); } double power(double x, int y) { if(y == 0) return 1; int sign = 1; if(y < 0) sign = -1; y = abs(y); double d = power(x, y/2); if(y%2 == 0) d = d*d; else d = x*d*d; if(sign == -1) return 1.0/d; else return d; } I am surprised that not a single person here had noticed that the guy asked to raise a DOUBLE to a given power. Men, double are not integers. Their exponent is stored in a part of their binary representation. If you multiply n times a double you will make n times a rounding error and n useless calculations. Just changed the binary part of the double that is related to its exponent, and here it is, your double has been raised to a given power, a you absolutely lost no precision, and you've made 0 calculations. This is basic stuff, every university teaches that to its students... floating numbers representation... I believe interviewer is expecting for this public static double Power(double x, int y) { double result = 1; bool isNegative = y 0) { if ((y & 1) > 0) { result *= x; } y = (y >> 1); x *= x; } if (isNegative) result = 1 / result; return result; } Verified C# static double Pow(double b, double exp) { if (exp == 0) return 1; else if (exp > 0) return b * Pow(b, exp - 1); else return 1 / Pow(b, -exp); } Does it get more compact? TD's answer is interesting, but not very useful. If you actually try it you'll find that since the double's base is 2, any changes to the exponent portion approximately multiply (or divide) numbers by a power of two. I say approximately here, since TD forgot to mention that the number itself isn't stored in float point numbers, only the digits after the implied 1. So yes, it's important to know how floating point numbers work, but modifying the exponent portion of a floating point number is a fundamentally incorrect solution. public double power(double num, int exp) { if(exp == 0) return 1; double res = 1; for(int e=Math.abs(exp);e>0;num*=num,e>>=1) { if( (e&1) == 1) res *= num; } return (exp>0)?res:1.0/res; } |

### Software Engineer at Google was asked...

Write a function that divides two numbers without using the divide '/' operator. 11 AnswersI had to use recursive subtraction or addition. But, I think I took too long a time to figure out the fastest code and I was typing it out in google docs while the interviewer was on the phone with me. I was nervous. It was my first ever interview. But, it was a heck of a experience. X * Y^(-1) One way is to iteratively count the number of times Xn = Xn-1 - Y >= Y. No recursion needed. Also, if Y is a power of 2, you can use a right-shift to get the answer...even faster. If the number space is sufficiently small, you can use a lookup table. Show More Responses int positionOfFirstAndOnlyBitSet(int m) { int pos = -1; int x = 0; for (; x > x) & 1) if (pos == -1) pos = x; else return -1; // found more than one bit } return pos; } int divide(int n, int m) { if (m == 1) return n; if (m == n) return 1; if (m > n) return 0; int pos = positionOfFirstAndOnlyBitSet(m); if (pos != -1) return n >> pos; // how manny times one can multiply m before going over n int x = 1; int mm = m; while (mm <= n) { mm += m; x++; } return x - 1; } assuming you want to be able to handle doubles, I like the idea of x * pow(y,-1.0); ... why make the answer more difficult for yourself than it needs to be? I got this question in facebook interview as well. You usually are not allowed to use floats, or pow(), or % And also you have to consider both +, - integers, so Steve M answer is not valid. public static int divide(int a, int b) { if(a < b) return 0; int div = b; int k = 1; while((div<<1) <= a) { div = div<<1; k = k<<1; } return k + (div == a ? 0 : divide(a-div,b)); } int num; int div; int rem; // assume only positive numbers for(i=0; num>=0 ; num-=div) { i++; rem=num; } printf("\ni: %s%d rem:%d", i, rem ); Victor, whats the complexity of your solution ? Binary search will work ? Let's say you need x/y. And only integral solution is needed i.e. 10/3 = 3 , not 3.33. This won't work if we need float as a result Pseudocode If x > 2) if mid*y == x : return mid if mid*y > x : hi = mid - 1 else: lo = mid + 1 return lo -------------------- Actually, it's quite simple. Recursively! function addTwo(x,y){ if (y === 0) { return x; } return addTwo( x ^ y, (x & y ) << 1); } addTwo(2,3) // 5 OR do it iteratively function addTwo(x, y) { // Iterate till there is no carry. while (y !== 0) { // Carry now contains common set bits of x and y. carry = x & y; // Sum of bits of x and y where at least one of the bits is not set. x = x ^ y; // Carry is shifted by one so that adding it to x gives the required sum. y = carry << 1; } return x; } |

### Software Engineer at Facebook was asked...

(a) first, write a function to calculate the hamming distance between two binary numbers (b) write a function that takes a list of binary numbers and returns the sum of the hamming distances for each pair (c) find a solution for (b) that works in O(n) time. 10 Answers(for question 1) public static String addBinaryStrings(String a, String b) { if ((null == a) || (null == b)) return null; return int2bstring(bstring2int(a) + bstring2int(b)); } public static int bstring2int(String a) { int sum = 0; int multiplier = 1; while (a.length() > 0) { String lastChar = a.substring(a.length()-2, a.length()); if (lastChar.equals("1")) sum += multiplier; multiplier *= 2; a = a.substring(0, a.length()-1); } return sum; } public static String int2bstring(int i) { if (0 == i) return "0"; String s = ""; while (i > 0) { if ((i % 2) == 0) { s = "1" + s; } else { s = "0" + s; } i /= 2; } return s; } (for question 2) public static int hammingDistance(String a, String b) { int numDigits = Math.max(a.length(), b.length()); int numDiff = 0; for (int i = 0; i < numDigits; i++) { String ithDigitA = extractDigit(a, i, numDigits); String ithDigitB = extractDigit(b, i, numDigits); if (!ithDigitA.equals(ithDigitB)) numDiff++; } return numDiff; } public static String extractDigit(String a, int i, int n) { if (i < n - a.length()) return "0"; return a.substring(i-n+a.length(), i-n+a.length()+1); } public static int setHamming(String[] a) { int numDiff = 0; int numDigits = 0; for (int i = 0; i < a.length; i++) { numDigits = Math.max(numDigits, i); } for (int i = 0; i < numDigits; i++) { int num0s = 0; int num1s = 0; for (String aa : a) { String ithDigitAA = extractDigit(aa, i, numDigits); if (ithDigitAA.equals("0")) { num0s++; } else { num1s++; } } numDiff += (num0s * num1s); } return numDiff; } A: int distance( int num1, int num2 ) { int distance; while( num1 != 0 && num2 != 0 ) { distance += num1&1!=num2&1; num1=num1>>1; num2=num2>>1; } return distance; } B: int distanceSum( std::vector nums ) { std::unordered_map digits; for( auto& num : nums ) { int digit = 1; while( num != 0 ) { digits[digit]+=num&1; num = num>>1; digit++; } } int distanceSum = 0; for( auto& p : digits ) { distanceSum += nums.length()-p.second; } return distanceSum; } Show More Responses for Problem C: /** * This solution is O(n) *I wrote it this way so its easier to be understood. **/ public int getHammingTotalFromBinaryNumbersList(List binaryNumbers){ Map binaryCounter = new HashMap; // Key is the _[1 or 0] on the binary number, so if you're at position 1, and you get 0, the key will be 0_1 String positionKey; int totalCount; int maxPosition = 0; foreach(String binaryNumber in binaryNumbers){ if(binaryNumber.Length-1 > maxPosition){ maxPosition = binaryNumber.Length-1; } for(i = 0; i 10001 10101 int GetHammingDistance(string s1, string s2) { Debug.Assert(s1.Length == s2.Length); int distance = 0; for(int i=0; i input, int n, out List distances) { if(n==2) { distances.Add(GetHammingDistance(input[0], input[1])); } for(int i=0; i {XY} GetAllPairsHammingDistance(zyx, 2, "")=> {XY, ZY} GetAllPairsHammingDistance(zxy, 2, "")=> {XY, ZY, ZX} XYZ 0 1 2 = 3 X Y Z | | | 0 1 | Y | |_ 0 1 = 2 Y Z | | | |_Z |_Y Problem 1. Add two binary numbers represented as ASCII strings with result also in form of an ASCII string // // Add two binary strings, the solution as follows: // 1) convert binary strings to unsigned integers // 2) Add resulting integers // 3) Convert the result back to binary string // 4) Reverse the string to obtain the resulting string // // // Convert binary ASCII string to unsigned integer by successive divide by 2 // uint binStr_to_uint(const char *pStr, int *size) { char *pEnd = pStr; uint num = 0; while(*pEnd) num = (num >= 1; //divide by 2 } *pStr = 0; //terminate the string } // Reverse a string void reverseString(char *pStr) { char *pEnd = pStr; while(*pEnd++) ; pEnd -= 2; //point to last string char char *pTmp; while(pStr size2 ? size1 : size2; char *pResult = malloc(sizeRes + 2); //add space for carry and EOS if(pResult == 0) return 0; uint_to_binStr(num2, pResult); reverseString(pResult); return (pResult); } Problem 2. Find Humming distance between two numbers. The problem did not specify what format the numbers are in, so I assumed unsigned integers. // // Find Humming distance // int hummingDistnce(uint num1, uint num2) { num1 = num1 ^ num2; //Humming distance is simply an XOR num2 = 0; while(num1) { ++num2; //count '1' bits num1 &= num1 - 1; } return num2; } The second part of the problem is simple, just traverse the list selecting pairs of numbers and call hummingDistance() function each time. Corrections to my previous example: // Convert binary ASCII string to unsigned integer by successive divide by 2 should say ....multiply by 2 instead of divide by 2 Another minor error fix, function uint_to_binStr(uint num) definition should also have a pointer to char parameter like below: void uint_to_binStr(uint num, char *pStr) Third correction, In function reverseString(), the temporary char variable should be defined as "char tmp;" instead of "char *pTmp", so the code block should be: char tmp; while(pStr < pEnd) { tmp = *pEnd; *pEnd-- = *pStr; *pStr++ = tmp; public static int hammingDistance(int a, int b) { int xor = a ^ b; int distance = 0; while (xor > 0) { xor = (xor - 1) & xor; distance++; } return distance; } public static int hammingDistance(int[] array) { int sum = 0; for (int i=0; i<32; i++) { int mask = 1 << i; int num0s = 0; int num1s = 0; for (int value : array) { if ((value & mask) != 0) { num1s++; } else { num0s++; } } sum += num0s * num1s; } return sum; } |