2012-10-01 47 views
3

我是C++開發新手,希望有人能夠幫助我處理我一直在嘗試做的事情。用整數的十進制表示計算不同位數的個數

舉個例子,我想要一個函數,給定一個整數輸入,返回它包含的不同位數。

因此,舉例來說,如果我有三個整數:

int a = 19876; 
int b = 25644; 
int c = 4444; 

如果我通過「A」到功能,我希望要返回的數字5。 如果將'b'傳遞給函數,我期望返回'4', 如果將'c'傳入函數,則返回1,因爲它們是不同數字的數目。

有人請說明我該如何實現這一目標嗎?

+0

您需要拆分出個別數字,以便對它們進行計數。 'a%10'是'a'的最右邊的數字; 「a/10」是「a」的其餘部分,最右邊的數字被刪除。 –

+0

有沒有你可以提供給我的任何鏈接,以便閱讀這種方法?我發現很難碰到,我通常使用搜索引擎相當好:)但我不能找到這麼容易 –

+0

我不知道任何東西,但它是一個基本的技術,當你需要將數值轉化爲其他。比如說,文本:'while(a!= 0){std :: cout <<(a%10 +'0'); a/= 10; }' –

回答

6

你的意思是你要找到不同的十進制數字的整數中的數字?

int distinct_digits(int value) { 
    std::ostringstream out; 
    out << value; 
    std::string digits = out.str(); 
    std::sort(digits.begin(), digits.end()); 
    return std::unique(digits.begin(), digits.end()) - digits.begin(); 
} 

(未編譯或測試,但其基本思想應該工作)

+0

對於延遲感到抱歉,我想用我的代碼進行測試,謝謝 –

+0

它是否可以根據所有情況調整此實現以適用於負面?它確定如果不是,只是好奇,看看你會如何模具:) –

+0

格式化值時,我會使用'std :: abs(value)'。 –

1

你可以計算出明顯的數字,但沒有辦法從'a'the value of the variable a;。您可以對其進行硬編碼 - 但這相當維護。

-1

如果你的意思是返回一個浮點數來得到一個小數只是返回它作爲一個浮點數,編譯器應該隱式類型轉換。這通常不是很好的代碼,但它的工作原理。更好的方法可能是將值交給臨時浮動像

float a_float = a; 
return a_float; 
+0

我很困惑。這是如何將整數'19876'轉換爲整數'5'? – Kevin

+0

此回覆不回答問題。 – bohney

5

使用mod運算符,你可以指望它:

int distinct(int a) 
{ 
    int ele[10]={0}; 

    if(a==0) return 1; 
    if(a<0) a=a*-1; 

    while(a) 
    { 
     int t=a%10; 
     ele[t]=1; 
     a=a/10; 
    } 

    for (i=0;i<10;i++) 
     if (ele[i]) 
      count++; 

    return count; 
} 

這將只工作兩個正數和負數數字。

+0

這真的很棒,也謝謝 –

+0

也編輯負數。 –

4

這可能更簡潔,但我正在幫助您瞭解解決方案的工作方式。

int digitCount(int number) { 
    // make an array to store whether you've seen a given digit 
    // note that there are 10 elements, one for each digit 
    // this will be conveniently indexed 0-9 
    bool digitSeen[10]; 

    // set each seen digit 
    int count = 0; 
    while (number != 0) { 
     // get the rightmost digit with the modulo operator (%) 
     int digit = number % 10; 
     if (digitSeen[digit] == false) { 
      // only count if this is the first time we have seen it 
      ++count; 
      digitSeen[digit] = true; 
     } 
     // pop off the right-most digit by dividing by 10 
     number /= 10; 
    } 

    return count; 
} 
+0

我感謝你評論你的解決方案,它幫助我了很多:) –

相關問題