蓝桥杯2013年D题错误代码

#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int n = 50;

string add(string a,string b)
{
    a = a.substr(a.find_first_not_of('0'));
    b = b.substr(b.find_first_not_of('0'));
    long long lena = a.length();
    long long lenb = b.length();
    long long len = max(lena,lenb);
    
    reverse(a.begin(),a.end());
    reverse(b.begin(),b.end());
    string ans(len,'0');
    for(int i = 0;i < lena;i++)
    {
        ans[i] = a[i];
    }
    int temp = 0;
    for(int i = 0;i < len;i++)
    {
        if(i < b.length())
            temp += (ans[i] - '0') + (b[i] - '0');
        else
            temp += (ans[i] - '0');
        ans[i] = temp % 10 + '0';
        temp = temp / 10;
    }
    
    reverse(ans.begin(),ans.end());
    return ans.substr(ans.find_first_not_of('0'));
    
}

int cmp(string a,string b)
{
    unsigned long i1 = a.find_first_not_of('0');
    if(i1 == string::npos)
        a = '0';
    else
        a.substr(i1);
    unsigned long i2 = b.find_first_not_of('0');
    if(i2 == string::npos)
        b = '0';
    else
        b.substr(i2);
    if(a.length() > b.length()) 
        return 1;
    else if (a.length() < b.length()) 
        return -1;
    else
    {
        if(a < b)
            return -1;
        if(a > b)
            return 1;
        else 
            return 0;
    }
}

string subtract(string a,string b)
{
    reverse(a.begin(),a.end());
    reverse(b.begin(),b.end());
    
    string ans(a.length(),'0');
    for(int i = 0;i < a.length();i++)
    {
        ans[i] = a[i];
    }
    
    for(int i = 0;i < b.length();i++)
    {
        if(a[i] >= b[i])
            ans[i] = a[i] - b[i] + '0';
        else
        {
            int k = 1;
            while(a[i + k] == '0')
            {
                ans[i + k] = '9';
                k++;
            }
            ans[i + k] = a[i + k] - '1' + '0';
            
            ans[i] = a[i] - '0' + 10 - (b[i] - '0') + '0';
        }
    }
    reverse(ans.begin(),ans.end());
    if(ans.find_first_not_of('0') == string::npos)
        return "0";
    return ans.substr(ans.find_first_not_of('0'));
}

void i2s(int t,string t_str)
{
    t_str = t % 10 + '0';
}

string divide(string a,string b)
{
    string ans = "0.";
    for(int i = 0;i < 101;i++)
    {
        int t = 0;
        while(cmp(a,b) >= 0)
        {
            a = subtract(a,b);
            t++;
        }
        string t_str;
        i2s(t,t_str);
        ans.append(t_str);
    }
    
    return ans;
}



int main()
{
    string a = "10";
    string b = "4";
    cout << divide(a,b) << endl;
    for(int i = 3;i <= n;i++)
    {
        
        string tmp = b;
        b = add(a,b);
        a = tmp;
    }
    
    //ab是斐波那契的n-1和n项
    string ans = divide(a,b);
//    cout << ans << endl; 
    
    return 0;
}

 

posted @ 2020-03-03 20:30  恶魔岛  阅读(163)  评论(0编辑  收藏  举报