function check short int algorithm [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This is my function and I need help....
I must try to catch the range of short int without error handler or try&catch.
I cant´t find my failure in this algorithm — I hope you can help me.
short int checkShortInt(char * myString)
{
short int i = 0;
short int len;
if((myString[i]=='+')||(myString[i]=='-')) i++;
for (len = i; myString[len] != '\0'; len++);
if(len-i>5) return(0);
if(myString[i+0]<'3') return(1);
if(myString[i+0]>'3') return(0);
if(myString[i+1]<'2') return(1);
if(myString[i+1]>'2') return(0);
if(myString[i+2]<'7') return(1);
if(myString[i+2]>'7') return(0);
if(myString[i+3]<'6') return(1);
if(myString[i+3]>'6') return(0);
if(myString[i+4]>'7') return(0);
return(1);
}

Note that the range covered by short is asymmetric when two's complement is used: it normally ranges from -32768 to 32767.
If the length of the value is smaller than 5, the string clearly fits into a short.

My two cents. Maybe overkill...
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <inttypes.h>
int checkShortInt(char *myString)
{
long long i = strtoll(myString, 0, 0);
return (i >= SHRT_MIN && i <= SHRT_MAX);
}

short int checkShortInt(char * myString)
{
short int i = 0;
int total = 0;
// Skip a leading +/- sign.
if((myString[i]=='+')||(myString[i]=='-')) i++;
while(myString[i] != '\0')
{
total = 10*total + myString[i]-'0';
++i;
}
if (SHRT_MIN <= total && total <= SHRT_MAX)
{
return total;
}
return 0;
}
Sample inputs and results:
checkShortInt("53") ==> 53
checkShortInt("+125") ==> 125
checkShortInt("0") ==> 0
checkShortInt("70345") ==> 0

Related

Wrote a program to get the binary output of a decimal, and the result is inverted [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
Below is the program for my assignment. All of it was given except the printing and logic. I searched many videos about it and did what they did, but 15's binary is 1111 and the result was 0000
#include <stdio.h>
#include <math.h>
// Function to convert decimal to binary
// The function is void type so, print the result inside the function
void decimal2Binary(int dec) {
// array to store binary number
int binaryNumber[32];
// Your logic goes here
// fill out the binaryNumber
// i to increment the loop and terminate
int i = 0;
// We are interested in positive numbers for now
while (dec > 0) {
// Please add your logic to build the binary array
binaryNumber[i] = dec%2;
dec = dec/2;
i++;
}
// Print the binary array.
printf("Binary: ");
for (int j = i - 1; j >= 0; j--) {
printf("%d",binaryNumber[i]);
}
}
// The main function goes here
// The main function calls the decimal2Binary
int main() {
int decimal = 15;
printf("Decimal: %d equal to ", decimal);
decimal2Binary(decimal);
return 0;
}
DECIMAL TO BINARY (RECURSIVE):
#include <stdio.h>
int find(int dec_num)
{
if (dec_num == 0)
return 0;
else
return (dec_num % 2 + 10 *
find(dec_num / 2));
}
int main()
{
int decimal_number;
scanf("%d", &decimal_number);
printf("%d", find(decimal_number));
return 0;
}
DECIMAL TO BINARY (ITERATIVE):
#include <stdio.h>
long dec_to_bin(int decimalnum){
int binarynum = 0;
int mod, place = 1;
while(decimalnum != 0){
mod = decimalnum % 2;
decimalnum = decimalnum/2;
binarynum = binarynum + (mod*place);
place = place*10;
}
return binarynum;
}
int main() {
int decimalnum;
scanf("%d", &decimalnum);
printf("enter a decimal number:\n %ld", dec_to_bin(decimalnum));
return 0;
}

How can I print the base two representation of a number without using any array in C? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to print my characters BEFORE the previously printed character using printf. For example:
printf("1")
printf("0")
would need to output:
01
Is there a way to do this? I cannot use arrays. To be clear I'm printing in base two (binary) representation using a divide by two algorithm:
for(int i = 0; i < 16; i++){ // 16 bit int
tmp = num % 2;
if(tmp == 1){
printf("1");
} else {
printf("0");
}
num /= 2;
}
The above code prints the binary representation backwards.
Here is my solution to print binary without using array. you can ignore initial zeros by adding another if condition.
#include<stdio.h>
int main(){
int num =50;
int i;
for(i=15;i>=0;i--){
if( (1<<i) & num){
printf("1");
}
else printf("0");
}
return 0;
}
output:
0000000000110010
Recursion can perform like a "print before". #rici
The below does not always print 16 digits, just the decimal digits needed.
void print_binary(unsigned n) {
// Break the digits into 2 groups: 1) the one least digit and 2) the rest.
unsigned last_digit = n/10;
unsigned all_the_other_more_significant_digits = n/10;
// Let us print those more significant digits first;
if (all_the_other_more_significant_digits > 0) {
print_binary(all_the_other_more_significant_digits);
}
// Now print the last digit
printf("%u", last_digit);
}

Implementation on atoi() function with base [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm going a bit mad implementing this function. I think I have narrow the algorithm down but I have some strange behavior for some value. It seems to work for most of the values and bases, but for string "1000" it simply returns 0.
Below the code:
// A C program for
// implementation of atoi
#include <stdio.h>
#include <stdint.h>
int val(char c)
{
if (c >= '0' && c <= '9')
return (int)c - '0';
else
return (int)c - 'A' + 10;
}
int32_t my_atoi(uint8_t * ptr, uint8_t digits, uint32_t base){
// Initialize result
digits = 0;
// Initialize sign as positive
int sign = 1;
// Initialize index of first digit
int i = 0;
// If number is negative,
// then update sign
if (*ptr == '-') {
sign = -1;
i++;
}
// Iterate through all digits and update the result
for (; *(ptr+i) != '\0'; ++i){
digits = (digits * base) + val(*(ptr+i));
printf("Digits of %d is:%d\n",i,digits);
}
// Return result with sign
return sign * digits;
}
// Driver program to test above functions
int main()
{
uint8_t str[] = "1000";
uint8_t val2=0;
int val = my_atoi(str, val2, 16);
printf("%d \n", val);
return 0;
}
For the above code the output is:
Digits of 0 is:1
Digits of 1 is:16
Digits of 2 is:0
Digits of 3 is:0
0
I simply cannot understand why digits becomes 0 after it has the value 16.
Any help will be greatly appreciated.
Your digits is a uint8_t so it just overflows to 0. You should make it a larger, signed, data type like int32_t or int64_t so the sign works properly and it doesn't overflow.

Converting bits in an array to a decimal number [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need a function (in the C language) which can convert the binary contents of an array, in this case myArray[8] {*MSB* 1, 1, 1, 1, 1, 1, 1, 1 *LSB*} into the decimal equivalent = 255.
Any ideas on how to solve this, as efficiently as possible, as it is being done on a microcontroller?
Using bitwise shifting
#include <stdio.h>
int main(void) {
char myArray[8] = {1,1,1,1,1,1,1,1};
int i;
int result = 0;
for (i=0; i<sizeof(myArray); i++){
result += myArray[sizeof(myArray)-i-1] << i;
}
printf("%d\n", result);
return 0;
}
One solution is to add and shift in a Horner scheme.
result = (...((myArray[0])<<1 + myArray[1])<< 1+ ... ) << 1 ... ) + myArray[8];
or in multiple expressions:
result = myArray[0];
result <<= 1;
result += myArray[1];
result <<= 1;
...
result += myArray[8];
This solution is for MSB.
set up the for loop
unsigned int result = myarray[0];
for (int i = 1; i < 8, i++);
{
result <<= 1;
result += myarray[i];
}
#include <stdio.h>
int main()
{
int a[8] = {1,1,1,1,1,1,1,1};
int n=8,dec=0;
int j=0,f;
for(int i=(n-1);i>=0;i--)
{
dec=(a[i]*(int)pow(2,j))+dec;
j++;
}
printf("The converted Decimal number is: %d",dec);
return 0;
}
Output: The converted Decimal number is: 255
The result is also available at: http://ideone.com/NQK0Il

find all the possible combination of coins, implementing by recursion [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Solve the problem by recursion:
using three type coins include 1 yuan, 2 yuan and 5 yuan, plus to 10 yuan, how many combinations?
The following is my code :
int coinNum(int num){
if(num>=0){
if(num==0)
return 1;
else
return coinNum(num-5)+coinNum(num-2)+coinNum(num-1);
}else
return 0;
}
int main(){
int num=coinNum(10);
printf("%d\n",num);//the result is 128
system("pause");
return 0;
}
What's the error of my recursion algorithm or what's your right code ?question supplement :1. (5,2,2,1) and (2,5,2,1) should be counted as 1 combination . 2. the following is my code of the enumeration algorithm .
void coin(){
int i,j,k,count=0;
for(i=0;i<=10;i++)
for(j=0;j<=5;j++)
for(k=0;k<=2;k++)
if((i+2*j+5*k)==10){
count++;
printf("one yuan :%d,2 yuan :%d,5 yuan :%d\n",i,j,k);
}
printf("总方法数%d\n",count);//the result is 10
}
Your code is counting the number of permutations that add up to 10. You want combinations. That means (5,2,2,1) and (2,5,2,1) should be counted as 1 combination.
In this case, the answer should be 10: (5,5), (5,2,2,1), (5,2,1,1,1), (5,1,..1), (2,2,2,2,2), (2,2,2,2,1,1), (2,2,2,1,1,1,1), (2,2,1,..1), (2,1,..1), and (1,..1).
Try this code:
int coinNum(int num, int *coins){
if (num == 0) return 1;
if (num < 0 || !*coins) return 0;
return coinNum(num - *coins, coins) + coinNum(num, coins+1);
}
int main(){
int coins[] = {5,2,1,0}; // don't forget the 0 or the program won't end
int num=coinNum(10,coins);
printf("%d\n",num); // the result is 10
system("pause");
return 0;
}
The code above tries all combinations until the sum equals or exceeds the desired sum. Note that this is not the most efficient algorithm to solve this problem, but the most simple one. For better algorithms, you should probably look for it at Computer Science Stack Exchange.
Another simple algorithm, using idea to generate not decreasing sequence of coins.
int coinNum(int num, int min_coin) {
if (num == 0) {
return 1;
} else if (num < 0) {
return 0;
} else {
int res = coinNum(num - 5, 5);
if (min_coin <= 1) {
res += coinNum(num - 1, 1);
}
if (min_coin <= 2) {
res += coinNum(num - 2, 2);
}
return res;
}
}
int main(){
int num = coinNum(10, 1);
printf("%d\n", num);
return 0;
}

Resources