当前位置:  开发笔记 > 编程语言 > 正文

使用java在base -2中创建二进制数组

如何解决《使用java在base-2中创建二进制数组》经验,为你挑选了1个好方法。



1> 11thdimensio..:

基数-2中的-8应该[0,0,0,1][0,1,0,1]符合定义val = sum{(A[i])*(-2)^i}

以下是处理负面基础的代码

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Binary {

    public static void main(String[] args) {
        System.out.println("Started");
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter an integer : ");
        int num = Integer.parseInt(scan.nextLine());
        System.out.println("Enter base to convert to: ");
        int base = Integer.parseInt(scan.nextLine());

        scan.close();

        Integer[] bitArray = convertToBaseArray(num, base);

        System.out.println(Arrays.toString(bitArray));
    }

    private static Integer[] convertToBaseArray(int num, int base) {
        if(base == 0) {
            throw new RuntimeException("base can not be 0");
        } else if(num < 0 && base > 0) {
            throw new RuntimeException("positive base can not produce negative number");
        }
        List bitList = new ArrayList();

        int absoluteBase = Math.abs(base);
        if(base == 1) {
            //this is not unique, creating shortest bit array
            for(int i = 0; i < Math.abs(num); i++) {
                bitList.add(1);
            }
        } else if(base == -1) {
            //this is not unique, creating shortest bit array
            int evenBit = num > 0 ? 0 : 1;
            int oddBit = 1-evenBit;

            for(int i = 0; i < 2*Math.abs(num); i+= 2) {
                bitList.add(oddBit);
                bitList.add(evenBit);
            }
            if(oddBit == 1) {
                bitList.remove(bitList.size() -1);
            }
        } else {
            while(num != 0) {
                int remainder = num % base;
                if(remainder < 0) {
                    remainder += absoluteBase;
                    num -= absoluteBase;
                }
                num = num / base;
                bitList.add(remainder);
            }
        }
        return bitList.toArray(new Integer[]{});
    }

}

以下是一些示例运行:

Started
Enter an integer : 
-8
Enter base to convert to: 
-2
[0, 0, 0, 1]

Started
Enter an integer : 
8
Enter base to convert to: 
-2
[0, 0, 0, 1, 1]

Started
Enter an integer : 
8
Enter base to convert to: 
-5
[3, 4, 1]

Started
Enter an integer : 
4
Enter base to convert to: 
1
[1, 1, 1, 1]

Started
Enter an integer : 
4
Enter base to convert to: 
-1
[1, 0, 1, 0, 1, 0, 1]

Started
Enter an integer : 
-4
Enter base to convert to: 
-1
[0, 1, 0, 1, 0, 1, 0, 1]

推荐阅读
wangtao
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有