Tencent test development interview questions

Alas, I interviewed a test development engineer from Tencent today, and my face was swollen. I came down to look up the information and talk about an interview question
. Numbers, prefixes and arrays + the combination of numbers with a remainder of 3 to find the law]

For example, if the string of 14533254 is only required to be in O(N) time, it can only traverse one cycle, and according to the law of numbers that can be divisible by 3 learned in primary school, all numbers can be divisible by 3. So use this to calculate.

The idea is to add the digits in turn to get an array, and then the above string of 14533254, then the array is {1,5,10,13,16,18,23,27}, and then each digit corresponds to 3, it becomes {1,2,1,1,1,0,2,0}; find sum0 (the number with a remainder of 0)=2, sum1 (the number with a remainder of 1)=4, sum2 (the number whose remainder is 2)=2, the calculation result is res=sum0+C(sum0,2)+C(sum1,2)+C(sum2,2); where C(sum0,2) is a
combination Number problem, let's take C(sum1,2) as an example to illustrate
:

C(sum1,2) means to randomly select two {1, 145, 1453, 14533} in the number of sum1, select two and remove the same from left to right, the part under the body must be divisible by 3;
code show as below:

#include<iostream>
#include<string>
#include<algorithm>

using namespace std;
int main()
{
	string str;
	while (cin >> str)
	{
		int len = str.length();
		
		int sum = 0;
		int sum0 = 0, sum1 = 0, sum2 = 0;
		for (int i = 0; i < len; i++)
		{
			sum += str[i] - '0';
			
			if (sum%3== 0)
				sum0++;
			else
				if (sum % 3 == 1)
					sum1++;
				else
					sum2++;
		}
		
		cout << "结果是:"<<sum0 + sum0 * (sum0 - 1) / 2 + sum1 * (sum1 - 1) / 2 + sum2 * (sum2 - 1) / 2 << endl;
	}
	return 0;
}

Reference: https://www.cnblogs.com/zhazhaacmer/p/9441372.html

Guess you like

Origin blog.csdn.net/qq_41841073/article/details/82889982
Recommended