题解 | #爬楼梯#C++暴力字符串加法解法

爬楼梯

https://www.nowcoder.com/practice/b178fcef3ed4448c99d7c0297312212d

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() 
{
    int i=0;
    int j=0;
    int n=0;
    cin>>n;
    if(n==1)
    {
        cout<<"1";
        return 0;
    }
    if(n==2)
    {
        cout<<"2";
    }
    else 
    {
        vector <string> a;
        a.push_back("1");
        a.push_back("2");
        for(i=2;i<n;i++)
        {
            string c;
            int len1=a[i-1].size();
            int len2=a[i-2].size();
            int len=max(len1,len2);
            if(len1<len)
            {
                reverse(a[i-1].begin(),a[i-1].end());
                for(j=len1;j<len;j++)
                {
                    a[i-1]+='0';
                }
                reverse(a[i-1].begin(),a[i-1].end());
            }
            else 
            {
                if(len2<len)
                {
                    reverse(a[i-2].begin(),a[i-2].end());
                    for(j=len2;j<len;j++)
                    {
                        a[i-2]+='0';
                    }
                    reverse(a[i-2].begin(),a[i-2].end());
                }
            }
            int count=0;
            for(j=len-1;j>=0;j--)
            {
                int m=a[i-1][j]-'0'+a[i-2][j]-'0'+count;
                if(m>=10)
                {
                    count=1;
                }
                else 
                {
                    count=0;
                }
                c+=m%10+'0';
            }
            if(count)
            {
                c+='1';
            }
            reverse(c.begin(),c.end());
            a.push_back(c);
        }
        cout<<a[n-1];
    }  
    return 0;
}

全部评论

相关推荐

阿里巴巴各部门年终奖开奖了,有人拿到了220w
真烦好烦真烦:拿命换钱呢,公司给你220万,肯定是因为你对公司的贡献大于220万,想想要多厉害多累才能达到
投递阿里巴巴集团等公司10个岗位 >
点赞 评论 收藏
分享
learYuan:🐕看了都摇头
点赞 评论 收藏
分享
码农索隆:我头回见校招简历把个人优势写在最前面的,是我老了吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务