C++ comparing two numbers by their digits

最后都变了- 提交于 2019-12-13 05:28:56

问题


I want to make a function, which returns true whenever two numbers provided on input are made up of the same digits (with no replacement).

For example, 543 and 435 should return true, 10001 and 11000 should return true, but 111222 and 122222 should return false.

I've read something about bitmasks but do not really get it, could You help me?


回答1:


The simplest way I can think to handle this is to use buckets. Create an std::vector of length 10 (one for each digit) and then increment an index whenever you run across the corresponding digit. Finish by comparing vectors:

bool compare_digits(int x, int y) {
    std::vector<int> x_vec(10), y_vec(10);
    while(x != 0) { //!= instead of > so that we can handle negatives
        x_vec.at(x%10)++; //increment whatever digit is in the 1's place
        x /= 10; //chop off the 1's place digit
    }

    while(y != 0) { //repeat for y
        y_vec.at(y%10)++;
        y /= 10;
    }

    //check if they had the same digits
    return (x_vec == y_vec);
}



回答2:


Two numbers a made up of the same digits, if the counts (number of occurrences) of each digit are the same. Here is some code for a general base (template parameter)

template<int base=10>
bool compare_digits(int x, int y)
{
    // 0 exclude trivial cases
    if(x > base*y || y > base*x)
        return false;
    // 1 count occurrences of digits in x
    int count[base]={0};
    for(; x; x/=base)
        ++ count[x%base];
    // 2 subtract counts of digits in y, if result < 0: return false
    for(; y; y/=base)
        if(--count[y%base] < 0)
            return false;
    // 3 check that count[]==0
    for(int i=0; i!=base; ++i)
        if(count[i]) return false;
    return true;
}


来源:https://stackoverflow.com/questions/52880654/c-comparing-two-numbers-by-their-digits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!