Objective C- How to add digits in a number?

久未见 提交于 2019-12-06 05:37:17

问题


How do I add the digits in a particular number for example if the number is 3234 the result should be 3+2+3+4 = 12?


回答1:


Something along the lines of this should do it:

int val = 3234;

int sum = 0;
while (val != 0) {
    sum += (val % 10);
    val = val / 10;
}

// Now use sum.

For continued adding until you get a single digit:

int val = 3234;

int sum = val;
while (sum > 9) {
    val = sum;
    sum = 0;
    while (val != 0) {
        sum += (val % 10);
        val = val / 10;
    }
}

// Now use sum.

Note that both of these are destructive to the original val value. If you want to preserve it, you should make a copy or do this in a function so the original is kept.




回答2:


Hope it is not your homework !

int sum = 0;
while (value!=0) {
  sum += value % 10;
  value = value / 10;
}


来源:https://stackoverflow.com/questions/4032702/objective-c-how-to-add-digits-in-a-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!