zoukankan      html  css  js  c++  java
  • 牛客网计算机考研复试-KY30-进制转换

    题目链接:点这里


    题目描述:
    将一个长度最多为30位数字的十进制非负整数转换为二进制数输出。


    思路:

    模拟十进制转为二进制的过程,用string存储该数,遍历这个string,每次保留模2的数,然后除2就行。如十进制123

    十进制 除二 模二
    123 61 1
    061 30 1
    030 15 0
    015 7 1
    007 3 1
    003 1 1
    001 0 1

    模二行从下往上就是对应的二进制1111011


    代码:

    #include <bits/stdc++.h>
    using namespace std;
    vector<int>ans;
    
    void convert(string s){
        int len = s.size();
        while(true){
            ///判断s是否已经全是0了
            bool e = true;
            for(int i=0;i<len;i++){
                if(s[i]!='0'){
                    e = false;
                    break;
                }
            }
            if(e)   ///s已经全是0了
                break;
            else
                ans.push_back((s[len-1]-'0')%2);///将s的最后一位模2,结果压进数组。
            ///s除2
            int t=0;///保存前面是否还有1
            for(int i=0;i<len;i++){
                int num = s[i]-'0';
                int m = t*10+num;
                //cout << "m: " << m << endl;
                s[i] = (m/2)+'0';
                t = num%2;
            }
        }
    }
    
    int main(){
        string x;
        while(cin >> x){
            //如果输入的是0,输出0
            if(x.length()==1 && x=="0"){
                cout << 0 << endl;
                continue;
            }
            ans.clear();///记得初始化vector数组
            convert(x);
            for(int i=ans.size()-1;i>=0;i--)
                cout << ans[i];
            cout << endl;
        }
        return 0;
    }
    
    
  • 相关阅读:
    LeetCode "Jump Game"
    LeetCode "Pow(x,n)"
    LeetCode "Reverse Linked List II"
    LeetCode "Unique Binary Search Trees II"
    LeetCode "Combination Sum II"
    LeetCode "Divide Two Integers"
    LeetCode "First Missing Positive"
    LeetCode "Clone Graph"
    LeetCode "Decode Ways"
    LeetCode "Combinations"
  • 原文地址:https://www.cnblogs.com/123-wind/p/14317319.html
Copyright © 2011-2022 走看看