本帖最后由 jy00228875 于 2013-1-29 02:39 编辑
- public class han2 {
- static String str1="00001001000001110000000000100001";
- static String str2="00101000000101110000010000100001";
- public static void main(String[] args) {
- System.out.print(getByteArr(str1,str2));
- }
- static int getByteArr(String str1,String str2){
- byte[] ba1=str1.getBytes();
- byte[] ba2=str2.getBytes();
- int count=0;
- for(int x=0;x<ba1.length;x++){
- if(ba1[x]!=ba2[x])
- count++;
- }
- return count;
- }
复制代码 做这题看错东西,以为是把字符串转成个二进制数再拿去比,然后算距离,后来准备回帖才发现转成字节数组,也顺便把这个二进制算的也贴出来
- public class han {
- static String str1="00001001000001110000000000100001";
- static String str2="00101000000101110000010000100001";
- public static void main(String[] args) {
- han h=new han();
- int b1=h.getBin(str1);
- int b2=h.getBin(str2);
- int b=b1^b2;
- System.out.println(getD(b));
- }
- public int getBin(String str){
- int bin=0;
- int length=str.length()-1;
- for(int x=0;x<str.length();x++){
- char a=str.charAt(x);
- int b=(int)a-48;
- if(b==1)
- bin=bin+(int)Math.pow(2, length-x);
- }
- return bin;
- }
- public static int getD(int b){
- int count=0;
- while(b>0){
- int getone=b%2;
- b=b/2;
- if(getone==1){
- count++;
- }
- }
- return count;
- }
- }
复制代码 |