0

それで、授業の課題で困っています。目標は、バイナリ整数 (0 または 1) のみで満たされた長さnのベクトルを取得することです。元。[1,1,0,1] ここで、v[0] = 1、v[1] = 1、v[2] = 0、v[3] = 1 です。関数 ItBin2Dec の出力は、以下を表す数字のベクトルを出力します。同じ整数。したがって、[1,1,0,1] => [1,3] (13 の場合)。私は優れたプログラマーではないので、与えられたアルゴリズムに従ってみました。アドバイスをいただければ幸いです。

/* Algorithm we are given

function ItBin2Dec(v)
Input: An n-bit integer v >= 0 (binary digits)
Output: The vector w of decimal digits of v

Initialize w as empty vector
if v=0: return w
if v=1: w=push(w,1); return w
for i=size(v) - 2 downto 0:
  w=By2inDec(w)
  if v[i] is odd: w[0] = w[0] + 1
return w

*/

#include <vector>
#include <iostream>

using namespace std;

vector<int> ItBin2Dec(vector<int> v) {
    vector<int> w; // initialize vector w
    if (v.size() == 0) { // if empty vector, return w
        return w;
    }
    if (v.size() == 1) { // if 1 binary number, return w with that number
        if (v[0] == 0) {
            w.push_back(0);
            return w;
        }
        else {
            w.push_back(1);
            return w;
        }
    }
    else { // if v larger than 1 number
        for (int i = v.size() - 2; i >= 0; i--) {
            w = By2InDec(w); // this supposedly will multiply the vector by 2
            if (v[i] == 1) { // if v is odd
                w[0] = w[0] + 1;
            }
        }
    }
    return w;
}

vector<int> By2InDec(vector<int> y) {
    vector<int> z;
    // not sure how this one works exactly
    return z;
}

int main() {
    vector<int> binVect; // init binary vect
    vector<int> decVect; // init decimal vect

    decVect = ItBin2Dec(binVect); // calls ItBin2Dec and converts bin vect to dec vect
    for (int i = decVect.size(); i >= 0; i--) { // prints out decimal value
        cout << decVect[i] << " ";
    }
    cout << endl;



    return 0;
}

何かをコーディングしなければならなかったので、少し錆びています。明らかに、最初にスケルトンを取得しようとしているだけで、まだ実際の入力を設定していません。実際の割り当てでは、2 進数のベクトルの乗算を求めてから、結果の数字のベクトルを出力しますが、最初にこれから始めて、そこから作業すると考えました。ありがとう!

4

1 に答える 1