C ++逐个比较整数

时间:2015-10-02 09:29:47

标签: c++ for-loop integer barcode zipcode

我正在尝试将5位数的zipcode转换为27位数的条形码(由0和1组成),反之亦然。条形码的第一个和最后一个数字始终为1.删除这些数字会保留25位数字。分为5位数,从左到右,数字编码值为7,4,2,1,0。如果乘以相应的数字并计算总和,我们可以获得第一个邮政编码。例如,25位数的条形码是10100 10100 01010 11000 01001,邮政编码是99504.

1 x 7 = 7

0 x 4 = 0

1 x 2 = 2

0 x 1 = 0

0 x 0 = 0

sum = 9

#app/views/profiles/index.html.erb
<% @profiles.in_groups_of(3) do |group| %>
   <% group.each do |profile| %>
      <%= link_to "#{profile.user.first_name} #{profile.user.last_name}" %>
   <% end %>
<% end %>

现在我的问题是:在// main.cpp #include <iostream> #include <iomanip> #include "ZipCode.h" using namespace std; int main() { ZipCode zip1(99504); ZipCode zip2(12345); ZipCode zip3(67890); ZipCode zip4("100101010011100001100110001"); ZipCode zip5("110100001011100001100010011"); ZipCode zip6("100011000110101000011100101"); cout << "Digits" << " " << "Bar Code" << endl; cout << zip1.getZipCode() << setw(35) << zip1.getBarCode() << endl; cout << zip2.getZipCode() << setw(35) << zip2.getBarCode() << endl; cout << zip3.getZipCode() << setw(35) << zip3.getBarCode() << endl; cout << endl; cout << zip4.getZipCode() << setw(35) << zip4.getBarCode() << endl; cout << zip5.getZipCode() << setw(35) << zip5.getBarCode() << endl; cout << zip6.getZipCode() << setw(35) << zip6.getBarCode() << endl; return 0; } 中,如何比较每个整数值并评估为条形码?例如,在getZipCode(int num){}中,它显示为main()。由于99504是一个整数,如何评估9到条形码,然后评估下一个,依此类推?

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

std::string to_bar_code(unsigned int zip_code)
{
    const std::array<std::string, 10> digit {{
        "11000", "00011", "00101", "00110", "01001",
        "01010", "01100", "10001", "10010", "10100"
    }};
    return "1"
        + digit[(zip_code / 10000) % 10]
        + digit[(zip_code / 1000) % 10]
        + digit[(zip_code / 100) % 10]
        + digit[(zip_code / 10) % 10]
        + digit[zip_code % 10]
        + "1";
}

int to_zip_code(const std::string& bar_code)
{
    const std::map<std::string, int> digits = {
        {"11000", 0}, // special case
        {"00011", 1},
        {"00101", 2},
        {"00110", 3},
        {"01001", 4},
        {"01010", 5},
        {"01100", 6},
        {"10001", 7},
        {"10010", 8},
        {"10100", 9}
    };
    const std::string bar_digits[5]{
         {bar_code, 1, 5},
         {bar_code, 6, 5},
         {bar_code, 11, 5},
         {bar_code, 16, 5},
         {bar_code, 21, 5}
    };
    unsigned int res = 0;
    for (const auto& d : bar_digits)
    {
        res *= 10;
        res += digits.at(d);
    }
    return res;
}

Live Demo

相关问题