蓝桥杯 整数拼接(思维)

题解看这:https://blog.csdn.net/weixin_44775484/article/details/107442900 

 // #pragma GCC optimize(2)
 #include <iostream>
 #include <cstdio>
 #include <algorithm>
 #include <queue>
 #include <cmath>
 #include <string>
 #include <vector>
 #include <stack>
 #include <map>
 #include <sstream>
 #include <cstring>
 #include <set>
 #include <cctype>
 #include <bitset>
 #define IO                       \
     ios::sync_with_stdio(false); \
     // cout.tie(0);
 using namespace std;
//int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
typedef unsigned long long ULL;
typedef long long LL;
typedef pair<int, int> P;
const int maxn = 2e5 + 10;
const int maxm = 2e5 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const LL mod = 1e9 + 7;
const double pi = acos(-1);
LL a[maxn];
LL b[maxn];   // ÿһ¸ö a[i] µÄλÊý 
LL c[12][maxn]; // a[i] µÄ 10 µÄ£¨1~10£©´Î·½ ¶Ô kÈ¡Óà
LL n,k,ans=0;
LL qpow(LL a,LL b)
{
	LL ans=1;
	while(b)
	{
		if(b&1)
			ans=ans*a%k;
		a=a*a%k;
		b=b>>1;
	}
	return ans%k;
}
int main()
{
#ifdef WXY
	freopen("in.txt", "r", stdin);
	// freopen("out.txt", "w", stdout);
#endif
	cin>>n>>k;
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
		b[i]=log10(a[i])+1; 
	}	 
	for(int i=0;i<n;i++)
	{
		ans+=c[b[i]][(k-a[i]%k)%k];
		for(int j=1;j<=10;j++)
			c[j][a[i]%k*qpow(10,j)%k]++;
	}
	reverse(a,a+n);
	reverse(b,b+n);
	memset(c,0,sizeof c);
	for(int i=0;i<n;i++)
	{
		ans+=c[b[i]][(k-a[i]%k)%k];
		for(int j=1;j<=10;j++)
			c[j][a[i]%k*qpow(10,j)%k]++;

	}
	cout<<ans;
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
题目描述 给定两个正整数 a 和 b,将它们拼接起来得到一个新的整数。 例如,a=12,b=34,则拼接后得到的新整数为 1234。 输入格式 输入共两行,第一行为正整数 a,第二行为正整数 b。两个数字都不超过 10000 位。 输出格式 输出一个整数,表示拼接后的新整数。 样例输入 12 34 样例输出 1234 算法1 (字符串拼接) $O(n)$ 将两个整数转化为字符串,然后将它们拼接起来,最后将拼接后的字符串转化为整数输出即可。 时间复杂度 字符串拼接的时间复杂度为 O(n),其中 n 表示两个整数的位数。 空间复杂度 需要额外 O(n) 的空间存储字符串。 Python 代码 a = input().strip() b = input().strip() c = int(a + b) print(c) 算法2 (字符串迭代) $O(n)$ 根据题目要求,需要将两个整数拼接起来,可以将两个整数转化为字符串后,通过迭代的方式将两个字符串拼接起来,最后将拼接后的字符串转化为整数输出即可。 时间复杂度 字符串迭代的时间复杂度为 O(n),其中 n 表示两个整数的位数。 空间复杂度 需要额外 O(n) 的空间存储字符串。 Python 代码 a = input().strip() b = input().strip() c = '' for i in a: c += i for j in b: c += j c = int(c) print(c) 算法3 (数学运算) $O(logn)$ 根据题目要求,需要将两个整数拼接起来,可以通过数学运算实现。 设第一个整数为 a,第二个整数为 b,其位数分别为 len1 和 len2。 将第二个整数 b 乘以 10 ^ len1,然后加上第一个整数 a 即可得到拼接后的结果。 时间复杂度 时间复杂度为 O(logn),其中 n 表示两个整数的位数。 空间复杂度 只需要额外 O(1) 的空间存储变量。 Python 代码 a = input().strip() b = input().strip() c = int(b) + int(a) * (10 ** len(b)) print(c)

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值