题目描述:
两个整数之间的汉明距离是指两个数字与二进制比特的不同位置对应的数量。
给定两个整数x和y,计算它们之间的汉明距离。
注意:
0x,y 231。
样品:
输入: x=1,y=4
输出: 2
说明:
1(001 )4(010 )上面的箭头表示与二进制位对应的不同位置。
资料来源:力扣)。
链接: https://leet code-cn.com/problems/hamming-distance
版权归互联网所有。 商业转载请联系官方许可证。 非商业转载请注明出处。
解法:
class solution { publicinthammingdistance (intx,int y ) inta=x^y; strings=integer.tobinarystring (a ); int count=0; char[] ch=s.toCharArray (; for(intI=0; i ch.length; I ) if(ch[I]=='1' ) count; }返回计数; }} 一行代码,来源题解:
class solution { publicinthammingdistance (intx,int y ) returninteger.bitcount ) x^y; }bitcount(intI )返回给定int值的二进制补码表示形式的一位数。