Home > database >  A function that takes an integer and inserts zeros between its digits
A function that takes an integer and inserts zeros between its digits

Time:12-10

The function should take the address of the integer and modify it by inserting zeros between its digits. For example:

insert_zeros(3) //3
insert_zeros(39) //309
insert_zeros(397) //30907
insert_zeros(3976) //3090706
insert_zeros(39765) //309070605

My code:

#include <stdio.h>
#include <math.h>

void insert_zeros(int* num);

int main() {

    int num;

    printf("Enter a number:");
    scanf("%d", num);

    insert_zeros(&num);

    printf("Number after inserting zeros: %d", num);

    return 0;
}

void insert_zeros(int* num){
    int count = 0;
    int tmp = *num;

    //Count the number of digits in the number
    while(tmp != 0){
        tmp /= 10;
        count  ;
    }

    //calculating the coefficient by which I will divide the number to get its digits one by one
    int divider = (int)pow(10, count-1);
    int multiplier;

    tmp = *num;
    *num = 0;

    /*
    The point at which I'm stuck
    Here I tried to calculate the degree for the number 10
    (my thought process and calculations are provided below)
    */
    (count >= 3)? count  = (count/2): count;

    //the main loop of assembling the required number
    while (count >= 0){
        multiplier = (int)pow(10, count);       //calculating a multiplier
        *num  = (tmp / divider) * multiplier;   //assembling the required number
        tmp %= divider;                         //removing the first digit of the number
        divider /= 10;                          //decreasing divider
        count -= 2;                             //decreasing the counter,
                                                //which is also a power of the multiplier (witch is 10)
    }
}

My idea consists of the following formula:

For number "3" I shold get "30" and it will be:
30 = (3 * 10^1) - the power is a counter for number "3" that equals 1.

For number "39" it will be "309":
309 = (3 * 10^2) (9 * 10^1)

For number "397" it will be "30907":
30907 = (3 * 10^4) (9 * 10^2) (7 * 10^0)

For number "3976" it will be "3090706":
3090706 = (3 * 10^6) (9 * 10^4) (7 * 10^2) (6 * 10^0) - with each iteration power is decreasing by 2

For number "39765" it will be "309070605":
309070605 = (3 * 10^8) (9 * 10^6) (7 * 10^4) (6 * 10^2) (5 * 10^0)
And so on...

For a 3-digit number, the start power should be 4, for a 4-digit number power should be 6, for a 5-digit it should be 8, for 6-digit it should be 10, etc.

That algorithm works until it takes a 5-digit number. It outputs a number like "30907060" with an extra "0" at the end. And the main problem is in that piece of code (count >= 3)? count = (count/2): count;, where I tried to calculate the right power for the first iterating through the loop. It should give the right number to which will be added all the following numbers. But it only works until it gets a 5-digit number.

To be honest, so far I don't really understand how it can be realized. I would be very grateful if someone could explain how this can be done.

CodePudding user response:

As noted in comments, your use of scanf is incorrect. You need to pass a pointer as the second argument.

#include <stdio.h>
#include <math.h>

int main(void) {
    int num;
    scanf("%d", &num);

    int num2 = 0;
    int power = 0;

    while (num > 0) {
        num2  = (num % 10) * (int)pow(10, power);
        num /= 10;
        power  = 2;
    }

    printf("%d\n", num2);

    return 0;
}

CodePudding user response:

Adapting some code just posted for another of these silly exercises:

int main() {
    int v1 = 12345; // I don't like rekeying data. Here's the 'seed' value.

    printf( "Using %d as input\n", v1 );

    int stack[8] = { 0 }, spCnt = -1;
    // Peel off each 'digit' right-to-left, pushing onto a stack
    while( v1 )
        stack[   spCnt ] = v1, v1 /= 10;

    if( spCnt == 0 ) // Special case for single digit seed.
        v1 = stack[ spCnt ] * 10;
    else
        // multiply value sofar by 100, and add next digit popped from stack.
        while( spCnt >= 0 )
            v1 = v1 * 100   stack[ spCnt-- ];

    printf( "%d\n", v1 );

    return 0;
}

There's a ceiling to how big a decimal value can be stored in an int. If you want to start to play with strings of digits, that is another matter entirely.

CodePudding user response:

There's an easy recursive formula for inserting zeros: IZ(n) = 100*IZ(n/10) n.

That gives a very concise solution -- here the test cases are more code than the actual function itself.

#include <stdio.h>
#include <stdint.h>

uint64_t insert_zeros(uint64_t n) {
    return n ? (100 * insert_zeros(n / 10)   n % 10) : 0;
}

int main(int argc, char **argv) {
    int tc[] = {1, 12, 123, 9854, 12345, 123450};
    for (int i = 0; i < sizeof(tc)/sizeof(*tc); i  ) {
        printf("%d -> %lu\n", tc[i], insert_zeros(tc[i]));
    }
}

Output:

1 -> 1
12 -> 102
123 -> 10203
9854 -> 9080504
12345 -> 102030405
123450 -> 10203040500

CodePudding user response:

I thought it would be fun to do with recursion and also handle larger numbers.

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

void insert_helper(int num, int64_t *ret)
{
    if (num > 10)
    {
        insert_helper(num / 10, ret);
    }
    *ret *= 100ll;
    *ret  = (num % 10) * 10ll;
}

void insert_zeros(int64_t *num)
{
    int64_t ret = 0;
    if (*num >= 10)
    {
        insert_helper(*num / 10, &ret);
        ret *= 10ll;
        ret  = *num % 10;
    }
    else
    {
        ret = *num % 10 * 10;
    }
    *num = ret;
}

int main() 
{
    for (int i = 0; i < 5;   i)
    {
        int num;
        scanf("%d", &num);

        int64_t result = num;
        insert_zeros(&result);

        printf("%d -> %" PRId64 "\n", num, result);
    }

    return 0;
}

Input: 3 39 397 3976 39765 Output:

3 -> 30
39 -> 309
397 -> 30907
3976 -> 3090706
39765 -> 309070605

Demo

CodePudding user response:

EDIT: If this were in Java, this would be a solution, but the problem is in C, which I'm not sure if this can convert to C.

This may be a lot easier if you first convert the integer to a string, then use a for loop to add the zeros, then afterward reconvert to an integer. Example:

int insert_zeros(int num) {

    String numString = Integer.toString(num);
    String newString = "";
    
    int numStringLength = numString.length();
    for (int i = 0; i < numStringLength; i  ) {
        newString  = numString[i];

        // Only add a 0 if it's not the last digit (with exception of 1st digit)
        if (i < numStringLength - 1 || i == 0) newString  = '0';
    }

    return Integer.parseInt(newString);
}

I think this should give you your desired effect. It's been a little bit since I've worked with Java (I'm currently doing JavaScript), so I hope there's no syntax errors, but the logic should all be correct.

  • Related