C ++通过数字比较两个数字 [英] C++ comparing two numbers by their digits

查看:84
本文介绍了C ++通过数字比较两个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数,当输入中提供的两个数字由相同的数字组成(不替换)时,该函数返回true。

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).

例如, 543和435应该返回true,10001和11000应该返回true,但是111222和122222应该返回false。

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?

推荐答案

我认为处理此问题的最简单方法是使用存储桶。创建一个长度为10的 std :: vector (每个数字一个),然后在每次遇到相应数字时递增索引。通过比较向量来完成:

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);
}

这篇关于C ++通过数字比较两个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆