codewars041: 數組按字節反轉

Data Reverse

Solution:

public class Kata{
    public static int[] DataReverse(int[] data){
        final int bytes = data.length / 8;
        if(bytes == 1){
            return data;
        }
        int[] rslt = new int[data.length];    
        int index = 0;
        for(int i = bytes - 1; i >=0; i--){
            for(int j = 0; j < 8; j++){
                rslt[index++] = data[i * 8 + j];
            }    
        }    
         return rslt;           
    }    
}

Example Test:

import java.util.*;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class DataReverseTest{
@Test
  public void Test1() {
    int[] data1= {1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0};
    int[] data2= {1,0,1,0,1,0,1,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1};
    assertArrayEquals(data2, Kata.DataReverse(data1));  
  }
  
  @Test
  public void Test2() {
    int[] data1= {0,0,1,1,0,1,1,0,0,0,1,0,1,0,0,1};
    int[] data2= {0,0,1,0,1,0,0,1,0,0,1,1,0,1,1,0};
    assertArrayEquals(data2, Kata.DataReverse(data1));  

  }    
}
相關文章
相關標籤/搜索