C# Solution Simple and Beats 90%


  • 0
    V
    public class Solution {
        public int HammingDistance(int x, int y) {
            int dist = x ^ y;
            int count = 0;
            while( dist != 0)
            {
                if((dist & 1) == 1) count++;
                dist = dist >> 1;
            }
            return count;
        }
    }
    

  • 0
    G

    Why your code is faster than mine...My code only beats 38%

    public class Solution {
        public int HammingDistance(int x, int y) {
            int counter = 0;
    		int r = x ^ y;
    		while (r > 0)
    		{
    			r = r & (r - 1);
    			counter++;
    		}
    
    		return counter;
        }
    }
    

  • 0
    V

    @G33K Its probably to do with the statement which has a subtraction operation as a part of the execution statement. Mine is all either bit operations or bool checks which are traditionally way faster than other math operations. Read more here

    https://en.wikipedia.org/wiki/Peephole_optimization

    Try to get rid of the subtraction and you will see a boost in your results!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.