Title:
For an integer X(1 ≤ x, y ≤ 1000), the definition operation rev(X) is to flip X by digit and remove leading 0. For example:
If X = 123, rev(X) = 321;
If X = 100, then rev(X) = 1. Now give the integers x and y, what is the required rev(rev(x) + rev(y))? Input Description: input as a line, x, y(1 ≤ x, y ≤ 1000), separated by spaces. Output Description: output the value of rev(rev(x) + rev(y)). Example: input: 123 100 output: 223
Algorithm description:
Method 1: find the corresponding relationship between integers and bits. For example, "123", first consider how to take out the numbers in reverse order, that is, how to take out 3, 2 and 1. The method is as follows:
And there is a relationship between integers and their bits: 321 = (3 * 10 + 2) * 10 + 1. Therefore, the following algorithm functions can be designed:
int rev(int n) { int m = 0; while(n!=0) { m = 10*m + n%10; n = n/10; } return m; }
Method 2: because the range of input parameters is: 1 ≤ x, y ≤ 1000, the number of each digit can be calculated in turn, and then recombined into the number after flipping according to each digit. The algorithm functions are as follows:
int rev(int n) { int m; int n_qian, n_bai, n_shi, n_ge; int m_qian, m_bai, m_shi, m_ge; n_qian = n/1000; n_bai = n%1000/100; n_shi = n%100/10; n_ge = n%10; if(0==n_qian) //n is three digits { m_bai = n_ge; m_shi = n_shi; m_ge = n_bai; m = m_bai*100 + m_shi*10 + m_ge*1; if(0==n_bai) //n is two digits { m_shi = n_ge; m_ge = n_shi; m = m_shi*10 + m_ge*1; if(0==n_shi) //n is a single digit { m_ge = n_ge; m = m_ge; } } } else //n is four digits { m_qian = n_ge; m_bai = n_shi; m_shi = n_bai; m_ge = n_qian; m = m_qian*1000 + m_bai*100 + m_shi*10 + m_ge*1; } return m; }
Full code:
#include <stdio.h> int rev(int n); int main(void) { int x, y ,m,m1,m2; scanf("%d %d", &x, &y); printf("%d\n", rev(rev(x) + rev(y))); return 0; } #if 1 / / method 1 int rev(int n) { int m = 0; while(n!=0) { m = 10*m + n%10; n = n/10; } return m; } #else / / method 2 int rev(int n) { int m; int n_qian, n_bai, n_shi, n_ge; int m_qian, m_bai, m_shi, m_ge; n_qian = n/1000; n_bai = n%1000/100; n_shi = n%100/10; n_ge = n%10; if(0==n_qian) //n is three digits { m_bai = n_ge; m_shi = n_shi; m_ge = n_bai; m = m_bai*100 + m_shi*10 + m_ge*1; if(0==n_bai) //n is two digits { m_shi = n_ge; m_ge = n_shi; m = m_shi*10 + m_ge*1; if(0==n_shi) //n is a single digit { m_ge = n_ge; m = m_ge; } } } else //n is four digits { m_qian = n_ge; m_bai = n_shi; m_shi = n_bai; m_ge = n_qian; m = m_qian*1000 + m_bai*100 + m_shi*10 + m_ge*1; } return m; } #endif
Among the above two solutions, method one has generality and method two has limitation, that is, it is necessary to know the range of the input number to make a special solution algorithm.
Program running results:
Welcome to scan the QR code on the left and follow my wechat public account (also searchable: zhengnian-2018)