逐位比较数字

时间:2014-03-06 22:26:07

标签: c++

我想编写一个比较数组中数字的函数,并删除包含相同数字的数字(例如1335 531)。删除部分没有问题,但我似乎无法弄清楚如何比较它们逐位数字,特别是当它们的长度不同时。任何想法都受到欢迎和赞赏。

1 个答案:

答案 0 :(得分:3)

 unsigned get_digit_mask(unsigned input) 
 {
     unsigned result = 0;
     unsigned digit;
     do {
         digit = input%10; //get the rightmost digit
         input/=10; //remove it from the number
         result |= (1<<digit); //set that bit of the result
     }while(input); //continue as long as there's more digits
     return result; //return bitmask of used digits
 }

如果在数字1335上使用此功能,它将返回设置了第1,第3和第5位的掩码。如果给函数编号531,它将返回一个设置了第1,第3和第5位的掩码。如果掩码相等,则数字包含相同的数字。