Easy

Let's say that number a feels comfortable with number b if a ≠ b and b lies in the segment [a - s(a), a + s(a)], where s(x) is the sum of x's digits.

How many pairs (a, b) are there, such that a < b, both a and b lie on the segment [l, r], and each number feels comfortable with the other (so a feels comfortable with b and b feels comfortable with a)?

Example

For l = 10 and r = 12, the output should be
comfortableNumbers(l, r) = 2.

Here are all values of s(x) to consider:

  • s(10) = 1, so 10 is comfortable with 9 and 11;
  • s(11) = 2, so 11 is comfortable with 9, 10, 12 and 13;
  • s(12) = 3, so 12 is comfortable with 9, 10, 11, 13, 14 and 15.

Thus, there are 2 pairs of numbers comfortable with each other within the segment [10; 12]: (10, 11) and (11, 12).

Input/Output

  • [execution time limit] 0.5 seconds (c)

  • [input] integer l

    Guaranteed constraints:
    1 ≤ l ≤ r ≤ 1000.

  • [input] integer r

    Guaranteed constraints:
    1 ≤ l ≤ r ≤ 1000.

  • [output] integer

    • The number of pairs satisfying all the above conditions.

[C] Syntax Tips

// Prints help message to the console
// Returns a string
char * helloWorld(char * name) {
    char * answer = malloc(strlen(name) + 8);
    printf("This prints to the console when you Run Tests");
    strcpy(answer, "Hello, ");
    strcat(answer, name);
    return answer;
}

더보기

Solution

int s(int x)
{
	int sum=0;

	while(x>0)
	{
		sum+=x%10;
		x/=10;
	}

	return sum;
}

int comfortableNumbers(int l,int r)
{
	int count=0;

	for(int i=l;i<=r;i++)
		for(int j=i-s(i);j<=i+s(i);j++)
			count+=j!=i&&j>=l&&j<=r&&i>=j-s(j)&&i<=j+s(j);

	return count/2;
}
728x90

'Codesignal' 카테고리의 다른 글

<Codesignal> Rectangle Rotation  (1) 2020.04.18
<Codesignal> Weak Numbers  (0) 2020.04.18
<Codesignal> Pages Numbering With Ink  (0) 2020.04.16
<Codesignal> Square Digits Sequence  (0) 2020.04.15
<Codesignal> Is Sum of Consecutive 2  (0) 2020.04.15

+ Recent posts