历年上机题-----进制转换

思路:一开始被误导了,想着用减法来模拟除法,后面超时了。

其实因为只需要做除2的操作,那么直接模拟除法的过程会更简单。就直接按照笔算除法的过程来模拟就行了。

#include <bits/stdc++.h>
using namespace std;
int main()
{
    #ifndef ONLINE_JUDGE
        freopen("in.txt","r",stdin);
        freopen("out.txt","w",stdout);
    #endif
    string s;
    int num[100];
    while(cin>>s)
    {
        for(int i=0;i<s.size();i++)
        {
            num[i]=s[i]-'0';
        }
        vector<int> ans;
        int n=s.size();
        for(int i=0;i<n;)
        {
            int remind=0;
            int res=0;
            for(int j=i;j<n;j++)
            {
                res = (remind*10+num[j]);
                num[j] = res/2;
                remind = res%2;
            }
            ans.push_back(remind);
            while(num[i]==0) i++;
        }
        reverse(ans.begin(),ans.end());
        for(int i=0;i<ans.size();i++)
        {
            cout<<ans[i];
        }
        cout<<endl;
    }
    return 0;
}
发布了449 篇原创文章 · 获赞 197 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/qq_40774175/article/details/105338525