Skip to content

Instantly share code, notes, and snippets.

@domitry

domitry/4-2.c

Created May 17, 2014
Embed
What would you like to do?
Mon-1 Homework No.4
#include <stdio.h>
#include <string.h>
int main(){
char buffer[100];
int i, num, pow2 = 1, result=0;
scanf("%99s", buffer);
num = strlen(buffer);
for(i=num-1;i>=0;i--){
if(buffer[i] == '1')result += pow2;
else if(buffer[i] != '0'){
printf("Invalid Format.");
return -1;
}
pow2 *= 2;
}
if(buffer[0] == '1')result = (pow2 - result)*(-1);
printf("the result is %d\n", result);
return 0;
}
#include <stdio.h>
#include <string.h>
#define DIGIT_NUM 40
void swap(char *a, char *b){
char c = *a;
*a = *b;
*b = c;
}
void strrvs(char *str){
int i, len = strlen(str);
for(i=0;i<len/2;i++)swap(str+i, str+(len-i-1));
}
int main(){
char result[DIGIT_NUM];
int input, cnt = 0, seek = 0;
unsigned int num;
scanf("%d", &input);
num = (unsigned int)input;
do{
result[seek++] = (num%2 ? '1':'0');
num/=2;
if(cnt++ % 4 == 3)result[seek++] = ' ';
}while(num!=0);
result[seek] = '\0';
strrvs(result);
printf("the result is %s\n", result);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment