我正在尋找一種高效且簡單的方法將整數分隔爲數字,但我需要從第一個開始將它們分開。將整數分成非數字的位數
下面是sepparate一個數字,數字的典型方式:
int main(int argc, char* argv[]) { //argc is going to be the number
while(argc != 0) {
cout << argc % 10 << endl;
argc /= 10;
}
return 0;
}
但是做這種方式,我會得到,例如,5437 - > 7,3,4,5 我想扭轉上訴順序,5,4,3,7。所以我創造了這個:
int main(int argc, char* argv[]) {
int rem = 1;
while(argc/rem > 10) //We increase the remainder until we get the same amount of digits than the number
rem *= 10;
while(argc != 0) {
cout << argc/rem << endl; //We take the cocient of the division, wich will be always the first digit
argc %= rem; //Now we discard that digit
rem /= 10; //And we decrease the number of digits of the remainder too
}
return 0;
}
事情是:是否有任何其他方式以較短/更簡單的方式做到這一點?
PS:我不能使用堆棧,列表或那種結構。
在此先感謝
遞歸是另一種方式。 –
我通常只有一個數組存儲,然後將其向前打印。 –
我無法想象不得不限制自己使用堆棧或列表,除非彙編語言是真正的目標。在6502中有各種各樣的小技巧可以使用。在缺少本地分割指令的多臺機器中,存在一種涉及三位移位的技巧,並根據何時添加來添加3或6。 6的意義在於它當然是10和16之間的差別。穆罕默德的答案看起來就像你應該使用的答案,即使「技術上」數組是一個堆棧。 –