- To print sum of digits:
- public class SumOfDigits {
- public static void main(String[] args) {
- int num = 67;
- System.out.println(getSumOfDigits(num));
- }
- public static int getSumOfDigits(int num) {
- int sum = 0;
- if(num<0)
- {
- return -3;
- }else if(num>99){
- return -2;
- }else if(num>0&&num<9){
- return -1;
- }
- while (num > 0) {
- int rem = num % 10;
- sum = sum + rem;
- num = num / 10;
- }
- return sum;
- }
- }
Output:13
To print sum of digits:
- Output:13
0 comments:
Post a Comment