2014-03-06 50 views
1

我想寫一個函數比較數組中的數字並刪除那些包含相同數字的數字(例如1335 531)。刪除部分不會引起任何問題,但我似乎無法確定數字瞭解如何逐個比較它們,特別是當它們不具有相同的長度時。任何想法都更受歡迎和讚賞。用數字比較數字

+0

提示:有一個'std :: unique'算法。 – chris

+0

我會使用'std :: to_string'將整數轉換爲字符串,然後比較數字。 – segfault

回答

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

正是我在想什麼。完美的作品! –

+0

它呢?其實我很驚訝,我甚至沒有測試過它 –