算法練習(xí)(二進(jìn)制求和)


public class SF {

public String test(String a, String b) {

char[] achars = a.toCharArray();

char[] bchars = b.toCharArray();

//反轉(zhuǎn)后得數(shù)組

? ? ? ? char[] A_Revert =new char[achars.length];

char[] B_Revert =new char[bchars.length];

int Aj =0;

int Bj =0;

for (int i = achars.length -1; i >=0; i--) {

A_Revert[Aj] = achars[i];

Aj++;

}

for (int i = bchars.length -1; i >=0; i--) {

B_Revert[Bj] = bchars[i];

Bj++;

}

int AOf10 =0;//A得十進(jìn)制

? ? ? ? int BOf10 =0;//B得十進(jìn)制

? ? ? ? for (int i = A_Revert.length -1; i >=0; i--) {

if (A_Revert[i] =='1') {

AOf10 = (int) (AOf10 + Math.pow(2, i));

}

}

for (int i =0; i < B_Revert.length; i++) {

if (B_Revert[i] =='1') {

BOf10 = (int) (BOf10 + Math.pow(2, i));

}

}

int sumOf10 = AOf10 + BOf10;

if (sumOf10 >0) {

String i = _2(sumOf10);

System.out.println(i);

return i;

}

return "0";

}

StringBuilders =new StringBuilder();

//十進(jìn)制轉(zhuǎn)換二進(jìn)制

? ? public String _2(int num) {

if (num>=2){

//不被整除

? ? ? ? ? ? if (num %2 !=0) {

s.insert(0,"1");

_2(num /2);

}else {

s.insert(0,"0");

_2(num /2);

}

}else{

s.insert(0,"1");

}

return s.toString();

}

public static void main(String[] args) {

SF S =new SF();

S.test("1010","1011");

//S.test("11", "1");

? ? }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容