在java中一次输入一位数输入

时间:2015-07-26 09:15:57

标签: java

我有一个包含字节值0或1的整数输入,它们之间没有任何空格,例如1010111101010010010101。我想从这些中创建一个[1,0,1,...],读取一个数字一时间

或者说我有整数输入为12和两个变量a和b 我想将1分配给a和2分配给b,我该怎么做?

2 个答案:

答案 0 :(得分:0)

public static List<Byte> split(final int number) {

    final List<Byte> output = new LinkedList<Byte>();

    int remainder = number;
    while (remainder > 0) {
        output.add(0, (byte) (remainder % 10));
        remainder = remainder / 10;
    }

    return output;
}

public static void testSplit(final int number) {
    System.err.printf("testSplit(%d): %s\n", number, split(number).toString());
}

public static void testSplits() {

    testSplit(10101001);
    testSplit(12);
}
  

testSplit(10101001):[1,0,1,0,1,0,0,1]

     

testSplit(12):[1,2]

答案 1 :(得分:0)

  

假设我有整数输入为12和两个变量a和b我想将1分配给a和2分配给b

您是否尝试这样做?

int input = 1234;
String a = "";
String b = "";
boolean flag = false;
while(input !=0) {
    if (flag) {
        a += Integer.toString(input % 10);
    } else {
        b += Integer.toString(input % 10);
    }
    flag = !flag;
    input /= 10;
}
a = new StringBuffer(a).reverse().toString();
b = new StringBuffer(b).reverse().toString();
System.out.println(a);
System.out.println(b);

输出结果为:

  

13

     

24

Run live

注意,我使用ab作为字符串,可以轻松转换为整数