gpt4 book ai didi

java - 协助 Java 程序计算二进制数字

转载 作者:行者123 更新时间:2023-12-02 12:11:44 26 4
gpt4 key购买 nike

我最近参加了计算机组织类(class),在其中学习二进制十六进制等,我自己尝试创建一个从 0 计数到输入数字的程序,但是计数是用二进制完成的。我遇到了一些麻烦,让自己困惑得难以置信,如果能得到一些澄清和帮助,我将不胜感激。具体来说,如何使用某种 for 循环高效且有效地用 0 和 1 替换包含先前二进制数的字符串的值。然而,我知道有一些方法可以直接将字符串转换为二进制;我想做这个更复杂的方法来练习。

package counting;
import java.util.Scanner;
public class counting
{

public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Hello, this is a number counter, please enter the integer you would like to count to");
int number = input.nextInt();
String start = "0000000000";
// 000~etc is used as the start simply because i'm not sure how to calculate how many digit places
//the number input by the user will have

StringBuilder cont = new StringBuilder(start);

System.out.println(start);

/*What i intend to do is have the binary loop counter continue until it reaches
* the number input by the user, afterwards, working in a right to left manner, start counting from
* 0 up to the number given by the user, starting with 0. then using another loop, still using
* the right to left manner, if there is a 0, it should be replaced with a 1, and if there is a
* 1, it should be replaced with a 0, and the character before it should be replaced with a 1, if there
* is no room, continue to the left until there is a space available for a 1 and then reset all values
* after the 1 back to zero, and resume counting. the way i see it is requires a for loop to be used
* as the current position of a cursor used to determine what changes must be made
*/

for(int i = 0; i < number; i++)
{
int l = start.length();
for(int n = 0; n <= number; n++)
{

for(int w = 1; w <= l; w++)
{

if (cont.charAt(l-w) == '0')
{
cont.setCharAt((cont.length()-w), '1');

System.out.println(cont);
}

else if (cont.charAt(l-w) == '1')
{
cont.setCharAt((cont.length()-w), '0');
cont.setCharAt((cont.length()-(w+1)), '1');

System.out.println(cont);
}

}
}
System.out.println(cont);
}
}

}

最佳答案

这是一个小循环,可以满足您的要求。您只需记住 2 的幂即可以二进制进行计数。

public static char flip(char c){
if(c == '0')
return '1';
else
return '0';
}

public static void main(String[] args) {
String start = "0000000000";

StringBuilder cont = new StringBuilder(start);

int number = (int)Math.pow(2,10);

for(int i = 0; i < number; i++)
{
if(i != 0){

int val = (int)Math.floor(i/2);

for(int j = 0; j <= val; j++){
// Flip any bit that when modded by 2^j == 0
if(i % Math.pow(2,j) == 0){

cont.setCharAt((cont.length() - (j + 1)), flip(cont.charAt(cont.length() - (j + 1))));
}
}
}

System.out.println(cont);

}
}

关于java - 协助 Java 程序计算二进制数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46496579/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com