JAVA初学急求eclipse没多久就要交作业了。 问题是这样的 要你输入一个2✀s Complement number

2025-01-05 17:34:39
推荐回答(2个)
回答(1):

我写了补码转反玛的方法
public class Cat {

public static void main(String[] args) {
String str = "10011101";//补码
String complment = getComplment(str);//反玛
String original = getOriginalFromComplment(complment);//原玛

System.out.println(str + "--->" + original);
}

private static String getOriginalFromComplment(String str) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < str.length(); i++){
sb.append(str.charAt(i) == '0'? "1": "0");
}

return sb.toString();
}

private static String getComplment(String str) {
String complement = null;

if(str.charAt(str.length()-1) == '1'){
StringBuilder sb = new StringBuilder();
sb.append(str.substring(0, str.length()-1));
sb.append("0");
complement = sb.toString();
}else{
char[] ary = str.toCharArray();

for(int i = ary.length; i > 0; i--){
if(ary[i-1] == '1'){
ary[i-1] = '0';
break;
}else{
ary[i-1] = '1';
}
}

complement = new String(ary);
}

return complement;
}
}

-------------
10011101--->01100011

回答(2):

倒数减一