Split int into single digits. How to handle zeroes - c

I am trying to create a function that will take an int and separately return the leftmost digit and the rest of the number.
int idigitizer(int *number) {
int i = 1;
int head = 0;
int tmp = 0;
tmp = *number;
while (tmp > 9) {
if ((tmp/i) < 10) {
head = tmp/i;
*number = *number - (head*i);
return head;
} else {
i = i*10;
}
}
number = 0;
return tmp;
}
idigitizer returns the leftmost part of the number and *number will carry the rest.
I will have a loop in my main that will keep calling idigitizer until all the digits of the number get separated.
The thing is I don't know how to handle zeroes and how to make this process terminate correctly when it is done with the last digit. Any help is welcome. Thanks in advance.
EDIT : To make it clearer. I don't want the possible zeroes in the middle of a number to get lost. If i get the number 100047 as input I want idigitizer to return:
return - *number
100047
1 00047
0 0047
0 047
0 47
4 7
7

I would use something like this instead:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int getFirstDigit( int number );
int getRestOfNumber( int number );
int getNumberOfMissingZeros (int number, int restOfNumber);
int main(int argc, char* argv[]){
int x = 500574;
int firstDigit;
int restOfNumber;
int n; /* loop index */
firstDigit = getFirstDigit(x);
restOfNumber = getRestOfNumber(x);
printf("The first digit of %d is %d.\n",x,firstDigit);
printf("The rest of the number is ");
for( n = 0; n<getNumberOfMissingZeros(x,restOfNumber); ++n ){
printf("0");
}
printf("%d.",restOfNumber);
return EXIT_SUCCESS;
}
int getFirstDigit( int number ){
return number / (int)floor( pow(10,floor(log10( (double)number ))) );
}
int getRestOfNumber( int number){
return number % (int)floor( pow(10,floor(log10( (double)number ))) );
}
int getNumberOfMissingZeros (int number, int restOfNumber){
int digitsOriginally;
int digitsInRestOfNumber;
digitsOriginally = floor(log10( (double)number ) );
digitsInRestOfNumber = floor(log10( (double)restOfNumber ) );
return digitsOriginally - digitsInRestOfNumber - 1;
}
The magic is in the expression (int)floor( pow(10,floor(log10( (double)number ))) ); This gets the size of the value, like for 52330, it would return 10000, since there are five digits in 52330. This makes it easy to extract the highest digit.

Given the precisely worded constraints of the problem: a function that will take an int and separately return the leftmost digit and the rest of the number it cannot be done, because it is impossible to represent the leading zeros in an integer, so passing back the "rest of the number" is bound to cause permanent loss of information
As the robot in Lost in Space would say, "It does not compute."

Putting an appropriate loop around something like this should work if I understand the question correctly.
//! Given a number return the least significant digit.
//! Return true if all went well. False otherwise. (Clearly we
//! can handle errors better.)
/*!
\param[in/out] n
The number to strip the least significant digit from.
\param[out] d
The least significant digit of n.
*/
bool digitize(int& n, int& d)
{
if ( n == 0 )
return false
else
{
d = n % 10;
n = n / 10;
return true;
}
}

Related

Inline sprintf() for defining string as num in C?

So a bit ago I was warming up and doing some very simple challenges. I came across one on edabit where you need to make a function to add the digits of a number and tell if the resulting number is "Oddish" or "Evenish"
(ie oddishOrEvenish(12) -> "Oddish" because 1 + 2 = 3 and 3 is odd)
so I solved it with some simple code
# include <stdio.h>
# include <stdlib.h>
char* odOrEv(int num);
int main(int argc, char* argv[]) {
printf("%s", odOrEv(12));
}
char* odOrEv(int num) {
char* strnum = (char*) malloc(11);
char* tempchar = (char*) malloc(2); // ik i can declare on one line but this is neater
int total = 0;
sprintf(strnum, "%d", num);
for (int i = 0; i < sizeof strnum; i++) {
tempchar[0] = strnum[i];
total += (int) strtol(tempchar, (char**) NULL, 10);
}
if (total % 2 == 0) return "Evenish";
return "Oddish";
}
and it worked first try! Pretty rudimentary but I did it. i then thought hey this is fun howabout I make it better, so I got it down to
# include "includes.h"
char* odOrEv(int num);
int main(int argc, char* argv[]) {
printf("%s", odOrEv(13));
}
char* odOrEv(int num) {
char* strnum = (char*) malloc(11);
int total = 0;
sprintf(strnum, "%d", num);
while (*strnum) total += (int) *strnum++;
return total % 2 == 0 ? "Evenish" : "Oddish";
}
just 5 lines for the function. Since I'm so pedantic though, I hate that I have to define strnum on a different line than declaring it since I use sprintf. I've tried searching, but I couldn't find any functions to convert int to string that I could use while declaring the string (e.x. char* strnum = int2str(num);). So is there any way to cut off that one line?
srry if this was too big just tried to explain everything
P.S. don't tell to use atoi() or stoi or any of those since they bad (big reason long to eplain) also I'd prefer if I didn't have to include any more directories but it's fine if I do
EDIT: forgot quote added it
To be honest it the one of the weirdest functions I have ever seen in my life.
You do not need strings, dynamic allocations and monster functions like sprintf or strtol.
char* odOrEv(int num)
{
int sum = 0;
while(num)
{
sum += num % 10;
num /= 10;
}
return sum % 2 == 0 ? "Evenish" : "Oddish";
}
You don't actually have to add the digits. The sum of even digits is always even, so you can ignore them. The sum of an odd number of odd digits is odd, the sum of an even number of odd digits is even. So just loop through the digits, alternating between oddish and evenish every time you see an odd digit.
You can loop through the digits by dividing the number by 10 and then checking whether the number is odd or even.
char *OddorEven(int num) {
int isOdd = 0;
while (num != 0) {
if (num % 2 != 0) {
isOdd = !isOdd;
}
num /= 10;
}
return isOdd ? "Oddish" : "Evenish";
}

Type casting failure in C program

As a C fresher, I am trying to write a recursive routine to convert a decimal number to the equivalent binary. However, the resultant string is not correct in the output. I think it has to be related to the Type casting from int to char. Not able to find a satisfactory solution. Can anyone help? Thanx in advance.
Code:
#include <stdio.h>
#include <conio.h>
int decimal, counter=0;
char* binary_string = (char*)calloc(65, sizeof(char));
void decimal_to_binary(int);
int main()
{
puts("\nEnter the decimal number : ");
scanf("%d", &decimal);
decimal_to_binary(decimal);
*(binary_string + counter) = '\0';
printf("Counter = %d\n", counter);
puts("The binary equivalent is : ");
puts(binary_string);
return 0;
}
void decimal_to_binary(int number)
{
if (number == 0)
return;
else
{
int temp = number % 2;
decimal_to_binary(number/2);
*(binary_string + counter) = temp;
counter++;
}
}
Should the casting store only the LSB of int in the char array each time?
Do not use global variables if not absolutely necessary. Changing the global variable in the function makes it very not universal.
#include <stdio.h>
char *tobin(char *buff, unsigned num)
{
if(num / 2) buff = tobin(buff, num / 2);
buff[0] = '0' + num % 2;
buff[1] = 0;
return buff + 1;
}
int main(void)
{
char buff[65];
unsigned num = 0xf1;
tobin(buff, num);
printf("%s\n", buff);
}
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int decimal, counter=0;
//char* binary_string = (char*)calloc(65, sizeof(char));
//C does not allow initialization of global variables with
//non constant values. Instead declare a static char array with 65 elements.
//Alternatively declare binary_string in the main function and allocate memory with calloc.
char binary_string[65];
void decimal_to_binary(int);
int main()
{
puts("\nEnter the decimal number : ");
scanf("%d", &decimal);
decimal_to_binary(decimal);
//*(binary_string + counter) = '\0';
// This is more readable:
binary_string[counter] = '\0';
printf("Counter = %d\n", counter);
puts("The binary equivalent is : ");
puts(binary_string);
return 0;
}
void decimal_to_binary(int number)
{
if (number == 0)
return;
else
{
int temp = number % 2;
//decimal_to_binary(number/2);
//you call decimal_to_binary again before increasing counter.
//That means every time you call decimal_to_binary, the value of count
//is 0 and you always write to the first character in the string.
//*(binary_string + counter) = temp;
//This is more readable
//binary_string[counter] = temp;
//But you are still setting the character at position counter to the literal value temp, which is either 0 or 1.
//if its 0, you are effectively writing a \0 (null character) which in C represents the end of a string.
//You want the *character* that represents the value of temp.
//in ASCII, the value for the *character* 0 is 0x30 and for 1 it is 0x31.
binary_string[counter] = 0x30 + temp;
counter++;
//Now after writing to the string and incrementing counter, you can call decimal_to_binary again
decimal_to_binary(number/2);
}
}
If you compile this, run the resulting executable and enter 16 as a number, you may expect to get 10000 as output. But you get00001. Why is that?
You are writing the binary digits to the string in the wrong order.
The first binary digit you calculate is the least significant bit, which you write to the first character in the string etc.
To fix that aswell, you can do:
void decimal_to_binary(int number){
if(number == 0){
return;
}
else{
int temp = number % 2;
counter++;
//Store the position of the current digit
int pos = counter;
//Don't write it to the string yet
decimal_to_binary(number/2);
//Now we know how many characters are needed and we can fill the string
//in reverse order. The first digit (where pos = 1) goes to the last character in the string (counter - pos). The second digit (where pos = 2) goes to the second last character in the string etc.
binary_string[counter - pos] = 0x30 + temp;
}
}
This is not the most efficient way, but it is closest to your original solution.
Also note that this breaks for negative numbers (consider decimal = -1, -1 % 2 = -1).

Palindrom checker,wrong output

I'm trying to solve Problem 4 -Project Euler and I am stucked. So I need a little help with my code. Here is the problem I am trying to solve:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int is_palindrom(int number, int revrse) {
char str1[6];
char str2[6];
sprintf(str1, "%d", number);
sprintf(str2, "%d", revrse);
return strcmp(str1, str2);
}
int main(void) {
int number, revrse;
int i, j, temp;
int maks;
for(i=999;i>99;i--)
for(j=999;j>99;j--) {
temp = number = i*j;
while (temp != 0) {
revrse = revrse * 10;
revrse = revrse + temp%10;
temp = temp/10;
}
if(is_palindrom(number, revrse)==0 && number > maks)
maks = number;
}
printf("%d",maks);
return 0;
}
The revrse var isn't initialized so there are rubbish in it. Remember to always init a variable!
Complementing the answer from #kleszcz, revrse must always be initialized before the while loop begins, otherwise, it will hold the previous value (and rubbish in the first iteration, as he intelligently pointed out).
Another issue is that you do not need the is_palindrome function. You can check directly if the numbers are equal.
To get the reversed form of your number properly, you need to first set an initial value for revrse of 0 for each iteration of your loop, otherwise the behavior is undefined. It also helps to set an initial value for maks to compare against. Finally, why use a function to check for palindromes when you can just check for equality between your number and its reverse?
int main()
{
int number;
int i,j,temp;
int maks = -1;
int revrse;
for(i=999;i>99;i--) {
for(j=999;j>99;j--) {
number = i*j;
revrse = 0;
temp=number;
while (temp != 0){
revrse = revrse * 10;
revrse = revrse + temp%10;
temp = temp/10;
}
if(number == revrse) {
if(number > maks) {
maks = number;
}
}
}
}
printf("%d",maks);
return 0;
}

UVA's 3n+1 wrong answer although the test cases are correct . . .?

UVA problem 100 - The 3n + 1 problem
I have tried all the test cases and no problems are found.
The test cases I checked:
1 10 20
100 200 125
201 210 89
900 1000 174
1000 900 174
999999 999990 259
But why I get wrong answer all the time?
here is my code:
#include "stdio.h"
unsigned long int cycle = 0, final = 0;
unsigned long int calculate(unsigned long int n)
{
if (n == 1)
{
return cycle + 1;
}
else
{
if (n % 2 == 0)
{
n = n / 2;
cycle = cycle + 1;
calculate(n);
}
else
{
n = 3 * n;
n = n + 1;
cycle = cycle+1;
calculate(n);
}
}
}
int main()
{
unsigned long int i = 0, j = 0, loop = 0;
while(scanf("%ld %ld", &i, &j) != EOF)
{
if (i > j)
{
unsigned long int t = i;
i = j;
j = t;
}
for (loop = i; loop <= j; loop++)
{
cycle = 0;
cycle = calculate(loop);
if(cycle > final)
{
final = cycle;
}
}
printf("%ld %ld %ld\n", i, j, final);
final = 0;
}
return 0;
}
The clue is that you receive i, j but it does not say that i < j for all the cases, check for that condition in your code and remember to always print in order:
<i>[space]<j>[space]<count>
If the input is "out of order" you swap the numbers even in the output, when it is clearly stated you should keep the input order.
Don't see how you're test cases actually ever worked; your recursive cases never return anything.
Here's a one liner just for reference
int three_n_plus_1(int n)
{
return n == 1 ? 1 : three_n_plus_1((n % 2 == 0) ? (n/2) : (3*n+1))+1;
}
Not quite sure how your code would work as you toast "cycle" right after calculating it because 'calculate' doesn't have explicit return values for many of its cases ( you should of had compiler warnings to that effect). if you didn't do cycle= of the cycle=calculate( then it might work?
and tying it all together :-
int three_n_plus_1(int n)
{
return n == 1 ? 1 : three_n_plus_1((n % 2 == 0) ? (n/2) : (3*n+1))+1;
}
int max_int(int a, int b) { return (a > b) ? a : b; }
int min_int(int a, int b) { return (a < b) ? a : b; }
int main(int argc, char* argv[])
{
int i,j;
while(scanf("%d %d",&i, &j) == 2)
{
int value, largest_cycle = 0, last = max_int(i,j);
for(value = min_int(i,j); value <= last; value++) largest_cycle = max_int(largest_cycle, three_n_plus_1(value));
printf("%d %d %d\r\n",i, j, largest_cycle);
}
}
Part 1
This is the hailstone sequence, right? You're trying to determine the length of the hailstone sequence starting from a given N. You know, you really should take out that ugly global variable. It's trivial to calculate it recursively:
long int hailstone_sequence_length(long int n)
{
if (n == 1) {
return 1;
} else if (n % 2 == 0) {
return hailstone_sequence_length(n / 2) + 1;
} else {
return hailstone_sequence_length(3*n + 1) + 1;
}
}
Notice how the cycle variable is gone. It is unnecessary, because each call just has to add 1 to the value computed by the recursive call. The recursion bottoms out at 1, and so we count that as 1. All other recursive steps add 1 to that, and so at the end we are left with the sequence length.
Careful: this approach requires a stack depth proportional to the input n.
I dropped the use of unsigned because it's an inappropriate type for doing most math. When you subtract 1 from (unsigned long) 0, you get a large positive number that is one less than a power of two. This is not a sane behavior in most situations (but exactly the right one in a few).
Now let's discuss where you went wrong. Your original code attempts to measure the hailstone sequence length by modifying a global counter called cycle. However, the main function expects calculate to return a value: you have cycle = calculate(...).
The problem is that two of your cases do not return anything! It is undefined behavior to extract a return value from a function that didn't return anything.
The (n == 1) case does return something but it also has a bug: it fails to increment cycle; it just returns cycle + 1, leaving cycle with the original value.
Part 2
Looking at the main. Let's reformat it a little bit.
int main()
{
unsigned long int i=0,j=0,loop=0;
Change these to long. By the way %ld in scanf expects long anyway, not unsigned long.
while (scanf("%ld %ld",&i,&j) != EOF)
Be careful with scanf: it has more return values than just EOF. Scanf will return EOF if it is not able to make a conversion. If it is able to scan one number, but not the second one, it will return 1. Basically a better test here is != 2. If scanf does not return two, something went wrong with the input.
{
if(i > j)
{
unsigned long int t=i;i=j;j=t;
}
for(loop=i;loop<=j;loop++)
{
cycle=0;
cycle=calculate(loop );
if(cycle>final)
{
final=cycle;
}
}
calculate is called hailstone_sequence_length now, and so this block can just have a local variable: { long len = hailstone_sequence_length(loop); if (len > final) final = len; }
Maybe final should be called max_length?
printf("%ld %ld %ld\n",i,j,final);
final=0;
final should be a local variable in this loop since it is separately used for each test case. Then you don't have to remember to set it to 0.
}
return 0;
}

Problems with Palindromes in C

I've written some code in C to try adn find whether or not a number is a Palindrome. The rule is that two 3 digit numbers have to be multiplied together and you have to find the highest palindrome. the answer should be 906609 but my code only gets to 580085.
the code:
#include <stdio.h>
#include <stdlib.h>
/* Intialise */
void CalcPalin();
int CheckPalin(int number);
/* Functions */
void CalcPalin()
{
int result = 0;
int palin = 0;
int FNumber = 0;
int FNumber2 = 0;
int number = 99;
int number2 = 100;
while(number2 < 1000)
{
number += 1;
/*times together - calc result*/
result = number * number2;
if(CheckPalin(result) == 1)
{
palin = result;
FNumber = number;
FNumber2 = number2;
}
if(number == 999)
{
number = 99;
number2 += 1;
}
}
printf(" Result = %d, by Multiplying [%d] and [%d]", palin, FNumber, FNumber2 );
}
int CheckPalin(int number)
{
int checknum, checknum2 = 0;
checknum = number;
while(checknum)
{
checknum2 = checknum2 * 10 + checknum % 10;
checknum /= 10;
}
if( number == checknum2)
return 1;
else
return 0;
}
int main( void)
{
CalcPalin();
return EXIT_SUCCESS;
}
Im pretty sure its a stupid answer and im over looking something simple but i cant seem to find it. Any help would be great
You have not tested whether the current result is higher than one old result. Add this check.
// test new result is higher than old palin before setting this as palin
if(CheckPalin(result) == 1 && palin < result)
Your algorithm print :
Result = 580085, by Multiplying [583] and [995]
It seems that you should find a way to increment more the 1st number. There is many possibility between 583 and 999 in order to get to 906609.
EDIT : In fact, you are looking for 993 * 913 = 906609.

Resources