【问题标题】:C++ Comparing integers one by oneC ++一一比较整数
【发布时间】:2015-10-02 09:29:46
【问题描述】:

我正在尝试将 5 位邮政编码转换为 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

总和 = 9

// 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() 中,它表示ZipCode zip1(99504);。既然 99504 是一个整数,那我如何将 9 计算为条形码,然后再计算下一个,以此类推?

【问题讨论】:

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


【解决方案1】:

您可以执行以下操作:

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

【讨论】:

    猜你喜欢
    • 2013-08-24
    • 2018-04-07
    • 2013-01-15
    • 2022-06-22
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    相关资源
    最近更新 更多