my_itoa 源码

#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
char *reverse(char *s)
{
	char temp;
	char *p = s;
	char *q = s;
	while(*q)
		++q;
	q--;
	while(q > p)
	{
		temp = *p;
		*p++ = *q;
		*q-- = temp;
	}
	return s;
}
char *my_itoa(int num,char *str,int radix)
{
	char index[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
	unsigned unum;
	int i=0,j,k; 
	if(radix==10&&num<0)
	{ 
		unum=(unsigned)-num; 
		str[i++]='-'; 
	} 
	else unum=(unsigned)num;
	do  
	{ 
		str[i++]=index[unum%(unsigned)radix]; 
		unum/=radix; 
	}while(unum); 
	str[i]='\0'; 
	if(str[0]=='-') k=1;
	else k=0; 
	char temp; 
	for(j=k;j<=(i-k-1)/2.0;j++) 
	{ 
		temp=str[j]; 
		str[j]=str[i-j-1]; 
		str[i-j-1]=temp; 
	} 
	return str; 
}
int BtoInt(const char* binaryString);
int main(int argc, char** argv)
{
	int test_case;
	/*
	freopen function below opens input.txt file in read only mode, and afterward,
	the program will read from input.txt file instead of standard(keyboard) input.
	To test your program, you may save input data in input.txt file,
	and use freopen function to read from the file when using scanf function.
	You may remove the comment symbols(//) in the below statement and use it.
	But before submission, you must remove the freopen function or rewrite comment symbols(//).
	*/
	//freopen("c:\\sample_input2.txt", "r", stdin);

	/*
	Read the test case from standard input.
	*/
	setbuf(stdout, NULL);

	for(test_case = 1; test_case <= 10; ++test_case)
	{
		int i;
		int N=0,Answer=0;
		/*
		Read the test case from standard input.65535
		*/
		scanf("%d",&N);
		if (N<=0)continue;
		char buf[16];
		my_itoa(N,buf,2);
		reverse(buf);
		Answer=BtoInt(buf);
		printf("#%d %d\n",test_case, Answer);
	}
	return 0;
}

int BtoInt(const char* binaryString)
{
	int size = strlen( binaryString);
	int * binary = new int [size];
	for (int i = 0; i < size; i++)
	{
		int temp = *(binaryString + i) - 48;
		binary[size-i-1] = temp;
	}
	
	int parseBinary = 0;
	for (int i = 0; i < size; i++)
	{
		int val=pow((*(binary + i) * 2.0),i);
		parseBinary+=val;
	}
	delete []binary;
	return parseBinary;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

linuf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值