進制轉換和大數除法

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <map>
#include <cstring>
using namespace std;

/*************************************************
trip0函數在程序中比較關鍵的做用是在除二運算後,去除 
高位的0,方便進行比較。 

*************************************************/ 
void trip0(string &s){
    while(!s.empty() && s[0] == '0')
        s.erase(s.begin());
}
string div_two(string s){
    string ans;
    int plus = 0;
    /*******************************************
    大數除法的部分 
    
    經過小時候所學習的基本的運算法則:經過除數除
    被除數的每一位 ,由高到低進行運算。餘數到下
    一位。plus是餘數。now是當前位的被除數。在編寫
    程序的時候出現了一個問題,程序一直不運算完成,
    經過調試發現是因爲plus未初始化,致使其中有一個
    很大的數。 
    
    ********************************************/
    for(int i = 0;i < s.length();i ++){
        int now = plus * 10 + (s[i] - '0');
        if(now >= 2){
            ans.push_back(char(now / 2 + '0'));
            plus = now % 2;
        }else{
            ans.push_back('0');
            plus = now;
        }
    }
    trip0(ans);
    return ans;
}
int main(){
    string tmp;
    while(cin >> tmp){
        string ans;
        trip0(tmp);
        while(!tmp.empty()){
            //此處的寫法值得借鑑。經過指針的訪問,實現起來十分的靈活。 
            int rail = (*(tmp.end() - 1) - '0') % 2;
            //string類型字符串的使用方式push_back 
            ans.push_back(char(rail + '0'));
            tmp = div_two(tmp);
        }
        reverse(ans.begin(),ans.end());
        if(!ans.empty()) cout << ans <<endl;
        else cout<< 0 << endl;
    }
    return 0;
}

 進制轉換 ios

相關文章
相關標籤/搜索