简体   繁体   中英

How to add 2 to each digit in a 4 digit number in C

I am trying to solve this tutorial practice question that doesn't have an answer that I can check my code against. The goal is to write a program to display numbers whose digits are 2 greater than the corresponding digits of the entered number. So if the number input is 5656 then the output number should be 7878 . I have figured out how to separate each number and add them, but I can't seem to get them to print in a four-digit sequence.


#include <stdio.h>

int main ()
{
    int n, one, two, three, four, final;
    scanf("%d", &n);

    one   = (n / 1000);
    n     = (n % 1000) + 2;
    two   = (n / 100) + 2;
    n     = (n % 100) + 2;
    three = (n / 10) + 2;
    n     = (n % 10) + 2;
    four  = (n / 1) + 2;
    n     = (n % 1) + 2;

    final = (one * 1000) + (two * 100) + (three * 10) + four;

    printf("%d", final);
    return 0;
}
#include <stdio.h>
int main()
{
     int n,a[4], final;
    scanf("%d", &n);
    for(int i=3;i>=0;i--)
    {
        a[i]=n%10+2;
        n/=10;
    }
    final = (a[0] * 1000) + (a[1] * 100) + (a[2] * 10) + a[3];
    printf("%d", final);
    return 0;
}

Below function works with N number of digits. Idea is to extract each digit from the input number and add its decimal position.

#include <stdio.h>

int power(int x, int y)
{
  int res = 1;
  for (;y>0;y--)
  {
    res *=x;
  }
  return res;
}
int main ()
{
    int n;
    scanf("%d", &n);
    int sum = 0;
    int i=0;
    while(n>0)
    {
       sum += ((n%10) +2)*power(10,i);
       i++;
       n /=10;
    }

    printf("%d", sum);
    return 0;

}

Another idea:

char str[10]; // enough to contain an int as string + 1
char *s = str+sizeof(str); // points to last char + 1
int n;

scanf("%d", &n);
*--s = 0;  // terminate the string

while(n) {
    *--s = (((n % 10)+2)%10) + '0'; // write a char from the end
    n /= 10;
}
printf("%s\n", s);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM