三行代碼實現十進位轉二進位,三行十進位

來源:互聯網
上載者:User

三行代碼實現十進位轉二進位,三行十進位

同學c++補考,找我幫忙寫十進位轉二進位的代碼,為了讓這同學能記住,所以就想寫的簡單些,然後沒想到居然能這麼簡單,感覺還不錯。直接上代碼:

void DtoB(int d){if(d/2)DtoB(d/2);cout<<d%2;}

考慮到有人很懶,喜歡複製就能用的代碼,所以下面貼一個帶主函數的完整代碼好了:

#include<iostream>using namespace std;void DtoB(int d){if(d/2)DtoB(d/2);cout<<d%2;}int main(){int n;cin>>n;DtoB(n);cout<<endl;return 0;}



初學Java,編程將十進位轉換成二進位,原始碼

public class ToBin {
public static String toBinString1(int i) {
return Integer.toBinaryString(i);
}

public static String toBinString2(int i) {
//int 型是4個位元組,32位,也就是說右移32次,每次移1位
StringBuilder builder = new StringBuilder();
int count = 32;
while(count-- > 0) {
builder.append((i & 1) == 1 ? "1":"0");
i = i>>1;
}
return builder.reverse().toString();
}

public static void main(String[] args) {
System.out.println(toBinString1(100));
System.out.println(toBinString2(100));
}
}
 
十進位轉換二進位C語言代碼

#include <stdio.h>

int main()
{
int a;
scanf("%d", &a);
int i=0;
int bin[32];

while(a>0)
{
bin[i]=a%2;
a/=2;
i++;
}
for(int j=i-1;j>=0;j--)
printf("%d",bin[j]);
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.