簡體   English   中英

cpp中的十進制右循環移位

[英]Decimal right cyclic shift in cpp

我需要這樣做,稱為“十進制右循環移位”。 例如,如果輸入為8652 ,則輸出將為2865

有沒有辦法在CPP中執行此操作而不轉換為字符串和字符串操作? 僅使用算術運算,循環並轉換為二進制。

如果數字中的位數嚴格為4,則可以執行以下操作:

int src = 1234;

int dest = (src / 10) + (src % 10) * 1000;

在此,如果src末尾為0 ,則dest為3位數。 您需要處理。

對於其他長度,您需要適當地調整代碼。

實際上,對於任何int數,都可以像這樣簡單,快速地完成:

#include <iostream>
using namespace std;

int concatenate (int x, int y)
{
        int pow = 10;
        while (y >= pow)
            pow *= 10;
        return x * pow + y;
}

int main()
{

        int rpm = 8652;

        // Cyclic Right Shift
        int lastDigit = rpm % 10;  //getting the last digit
        int otherDigits = (rpm - lastDigit)/10; //rest of the digits
        int CRS = concatenate(lastDigit, otherDigits); //concatenation
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM