将整数拆分为单独的数字

问题描述:

假设我有一个整数,9802,有没有办法可以将这个值分成四个单独的数字:9,8,0和0; 2?

Say I have an integer, 9802, is there a way I can split that value in the four individual digits : 9, 8, 0 & 2 ?

继续做模10和除10:

Keep doing modulo-10 and divide-by-10:

int n; // from somewhere
while (n) { digit = n % 10; n /= 10; }

这会将从最不重要到最重要的数字吐出。你可以清楚地将它概括为任何数字基础。

This spits out the digits from least-significant to most-significant. You can clearly generalise this to any number base.