牛客oj 习题6.12数字阶梯求和(大数相加)&&习题6.13大整数的因子(大数相除)

这篇博客介绍了如何使用C++处理字符串来解决牛客oj上的大数相加(数字阶梯求和)和大数相除(大整数的因子)的问题,指出虽然Java不熟悉,但C++对于这类问题较为简便。
摘要由CSDN通过智能技术生成

 

本来想用java干掉的,结果java实在是不懂,那只好继续c++处理字符串了,反正也不难,就是有点烦。

 

 

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <stack>
#include <cctype>
#include <cmath>
#include <climits>
 
using namespace std;
 
const int MAXN = 1005;
const int INF = INT_MAX;

string Plus(string big, string small){
	int lenbig = big.size();
	int lensmall = small.size();
	int cur = lensmall - 1;
	bool carry = false;
	int i;
	for(i = lenbig-1; i >= 0; i--){
		int num = (big[i]-'0') + (small[cur]-'0');
		if(carry){
			num++;
			carry = false;
		}
		if(num >= 10){
			num %= 10;
			carry = true;
		}
		big[i] = num + '0';
		cur--;
		if(cur == -1) break;
	}
	i--;
	while(carry){
		int num = (big[i]-'0') + 1;
		carry = false;
		if(num >= 10){
			num %= 10;
			carry = true;
		}
		big[i] = num + '0';
		i--;
		if(i == -1) break;
	}
	if(i == -1) big.insert(0, 1, '1');
	return big; 
}

int main(){
 //   freopen("in.txt", "r", stdin);
    int a, n;
    while(~scanf("%d %d", &a, &n)){
    	string str, ans;
    	str.insert(0, n, (a+'0'));
    	ans = str;
    	//str.erase(0, 1);
    	while(str.size() != 1){
    		str.erase(0, 1);
    		ans = Plus(ans, str);
    		//cout << ans << " " << str << endl;
    	}
    	cout << ans << endl;
    }
    return 0;
}

 

 

大整数相除,也是字符串问题,秒杀之。

 

 

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <stack>
#include <cctype>
#include <cmath>
#include <climits>
 
using namespace std;
 
const int MAXN = 1005;
const int INF = INT_MAX;

bool ZhengChu(string str, int x){
	int len = str.size();
	int remainder = 0;
	for(int i = 0; i < len; i++){
		int num = remainder*10 + (str[i] - '0');
		remainder = num%x;//只需保留余数即可 
	}
	if(remainder == 0) return true;
	else return false; 
}

int main(){
   // freopen("in.txt", "r", stdin);
    string c;
    while(cin >> c){
    	if(c == "-1") break;
    	vector<int> ans;
    	bool flag = false;
    	for(int i = 2; i <= 9; i++){
    		if(ZhengChu(c, i)){
    			flag = true;
    			ans.push_back(i);
    		}
    	}
    	if(flag){
    		bool tag = false;
    		for(int i = 0; i < ans.size(); i++){
    			if(tag) printf(" ");
    			tag = true;
    			printf("%d", ans[i]);
    		}
    		printf("\n");
    	}
    	else printf("none\n");
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值