zoukankan      html  css  js  c++  java
  • 小白月赛22 J : 计算 A + B

    J:计算 A + B

    考察点 : 高精度,字符串
    坑点   : 字符串中可能全是数字,或者 + 超过 1 个,需要进行特殊判断
    

    析题得侃:

    关于高精度的各种板子

    Code:

    #include <vector>
    #include <cstdio>
    #include <string>
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    string str;
    
    int T,n;
    
    int main(void) {
    	vector<int> add(vector<int> &A,vector<int> &B);
    	scanf("%d",&T);
    	while(T --) {
    		vector<int>a,b;
    		cin >> str;
    		int len = str.length();
    		int ans = 0;
    		for(int i = 0; i < len; i ++) {
    			if(str[i] == '+') {
    				ans ++;
    			}
    		}
    		if(str[0] == '+' || str[len - 1] == '+' || ans != 1) {
    			cout << "skipped" << endl;
    		} else {
    			bool flag = false;
    			for(int i = 0; i < len; i ++) {
    				if(str[i] == '+') {
    					flag = true;
    					continue;
    				}
    				if(flag == false) a.push_back(str[i] - '0');
    				else b.push_back(str[i] - '0');
     			}
     			reverse(a.begin(),a.end());
     			reverse(b.begin(),b.end());
     			vector<int>temp;
     			temp = add(a,b);
     			for(int i = temp.size() - 1; i >= 0 ; i --) {
     				cout << temp[i];
    			 }
    			 cout << endl;
    		}
    	}
    	return 0;
    }
    
    vector<int> add(vector<int> &A,vector<int> &B) {
        if(A.size() < B.size()) return add(B,A);         // 尽量用长的 + 短的,因为这样多余的部分我们就可以直接进行处理了
        vector<int> C;                                   // 设置一个 vector 类型的变量,用来作为返回的值
        int t = 0;
        for(int i = 0; i < A.size(); i ++) {
            t += A[i];
            if(B.size() > i) t += B[i];               		 // B 有一定的限制,不能一直加 呀 
            C.push_back(t % 10);
            t /= 10;                                    	 // 进位 
        }
        if(t) C.push_back(t);                                // 可能会多出来一个,例如3位数 + 3 位数 ,结果有可能是 4 位数
        return C;
    
    }
    
  • 相关阅读:
    git忽略已提交过的文件方法
    去除git版本控制
    写博客的初衷
    Substring with Concatenation of All Words
    Course Schedule
    Reverse Words in a String--not finished yet
    Repeated DNA Sequences
    Maximum Product of Word
    Odd Even Linked List
    Reorder List
  • 原文地址:https://www.cnblogs.com/prjruckyone/p/12354435.html
Copyright © 2011-2022 走看看