Bitset
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 12491 Accepted Submission(s): 9612
Problem Description
Give you a number on base ten,you should output it on base two.(0 < n < 1000)
Input
For each case there is a postive number n on base ten, end of file.
Output
For each case output a number on base two.
Sample Input
1 2 3
Sample Output
1 10 11
AC CODE:
#include<stdio.h>
int main()
{
int n;
while(~scanf("%d",&n))
{
int i,j,a[15];
for(i=15;i>=0;i--)
a[i]=n&1<<i?1:0;
for(j=15;j>=0;j--)
if(a[j]!=0)
break;
for(i=j;i>=0;i--)
printf("%d",a[i]);
printf("\n");
}
return 0;
}
扩展:
itoa函数
i ---- 需要转换成字符串的数字
10 ---- 转换数字的基数(即进制)。10就是说按10进制转换数字。还可以是2,8,16等等你喜欢的进制类型
运用实例:
1
2
3
4
5
6
7
8
9
10
|
#include <stdlib.h>
#include <stdio.h>
int
main(
void
)
{
int
number = 12345;
char
string[32];
itoa(number, string, 10);
printf
(
"integer = %d string = %s\n"
, number, string);
return
0;
}
|
radix 为转换时所用基数(保存到字符串中的数据的进制基数)
注意事项
itoa() 函数有3个参数:第一个参数是要转换的数字,第二个参数是要写入转换结果的目标字符串,第三个参数是转移数字时所用的基数(进制)。在上例中,转换基数为10,就意味着以10为转换进制。10:十进制;2:二进制...
itoa 并不是一个标准的C函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf。
标准库中有sprintf,功能比这个更强,用法跟printf类似:
char str[255];
sprintf(str, "%x", 100); //将100转为16进制表示的字符串。
本题itoa解题代码:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
char s[100];
int main()
{
int num;
while(cin>>num)
{
itoa(num,s,2);
puts(s);
}
return 0;