将整数拆分为单独的数字 [英] Split a integer into its separate digits
本文介绍了将整数拆分为单独的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个整数,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.
这篇关于将整数拆分为单独的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文