codewars067 - Delta Bits

Instructions

https://www.codewars.com/kata/538948d4daea7dc4d200023f/train/java

Solution:

public class DeltaBits {
    public static int convertBits(int a, int b) {

    	StringBuilder sba = new StringBuilder(Integer.toBinaryString(a)).reverse();
    	StringBuilder sbb = new StringBuilder(Integer.toBinaryString(b)).reverse();
    	int lena = sba.length();
    	int lenb = sbb.length();
    	int size = Math.min(lena, lenb);
    	int count = 0;
    	for(int i = 0; i <= size - 1; i++){
    		if(sba.charAt(i) != sbb.charAt(i)){
    				count++;
    		}
    	}
    	String extra = null;
    	if(lena > size){
    		extra = sba.toString();
    	}else if(lenb > size){
    		extra = sbb.toString();
    	}
    	if(extra != null){
    		for(int i = size; i <= extra.length() - 1; i++){
    			if(extra.charAt(i) == '1'){
    				count++;
    			}
    		}
    	}
    	
    	
      return count;
    
    }
}

Sample Tests:

import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class DeltaBitsTest{
    @Test
    public void test() throws Exception{
        assertThat(DeltaBits.convertBits(31, 14), is(2));
    }    
}
相關文章
相關標籤/搜索