7

I am a beginner java and trying to solve tricky problem

input=777
output should be 3
7+7+7=21 , 2+1=3;
From the above code if my input is 333 I am getting 9 as answer but when the sum is two digits(777=21) i am getting blank!

public static void main(String[] args) 
{

    int y=333;//if y is 777 i am getting blank
    int sum=0;
    String s;
    char []ch;
    do
    {
        s=String.valueOf(y);
        ch=s.toCharArray();

        if(ch.length>1) 
        {
            for(int i=0;i<ch.length;i++)
            {
            sum+=Character.getNumericValue(ch[i]);
            }
        }
        else
        {
        System.out.println(sum);
        }
        y=sum;      

    }while(ch.length>1);

}
Daniel Krom
  • 9,751
  • 3
  • 43
  • 44
Akhil Maripally
  • 109
  • 2
  • 9
  • 3
    This is one of those cases where a recursive solution would be better. Also this can be solved without the computationally expensive conversion to a string. Hint; use modulo and integer division by 10. – Bathsheba Aug 23 '15 at 09:05
  • @batsheba actually, modulo 9 works even better (for decimal; for binary you'd use modulo 1) – John Dvorak Aug 23 '15 at 12:32

8 Answers8

5

your code maybe loop forever

the right solution is the following below

public static void main(String[] args) throws ParseException {
int y = 777;// if y is 777 i am getting blank
int sum = 0;
String s;
char[] ch;
do {
    sum = 0;
    s = String.valueOf(y);
    ch = s.toCharArray();
    if (ch.length > 1) {
        for (int i = 0; i < ch.length; i++) {
            sum += Character.getNumericValue(ch[i]);
        }
    } else {
        System.out.println(ch[0]);
        break;
    }
    y = sum;
} while (ch.length > 1);
}

Maybe the better choice is the following code

public static void main(String[] args) throws ParseException {
    int y = 333;// if y is 777 i am getting blank
    int sum = 0;
    while (y % 10 != 0) {
        sum += y %10;
        y = y / 10;
        if (0 == y && sum >= 10) {
            y = sum;
            sum = 0;
        }
    }
    System.out.println(sum);
}

hope that helped

Javy
  • 944
  • 5
  • 9
3

For a task like this, it is best practise to use recursion.

The workflow in pseudocode would look like this:

procedure sumTillOneDigit(n)
    split n into it's digits
    s := sum of all digits of n

    if s has more than one digit:
        sumTillOneDigit(s)
    else
        output s

I am intentionally writing this in pseudocode, since this should help you solving the task. I will not give you a Java implementation, as it looks like a homework to me.

For more information see:

CharlyDelta
  • 938
  • 11
  • 31
2

You are getting that because you put the print statement in else condition..

Also note that to reset your sum value before reusing it. I.e. Set sum=0 at the start of do loop.

EDIT : there are two solutions to print you value 1. Don't put you print statements inside else conditions

  1. Print sum outside the do while loop
ashishmaurya
  • 1,196
  • 10
  • 18
2

First of all you must reset the value of sum variable.

and secondly you must print s in else condition and not the sum and rest is fine.

public static void main(String[] args) 
{

    int y=333;//if y is 777 i am getting blank
    int sum;
    String s;
    char []ch;
    do
    {
        sum=0;
        s=String.valueOf(y);
        ch=s.toCharArray();

        if(ch.length>1) 
        {
            for(int i=0;i<ch.length;i++)
            {
            sum+=Character.getNumericValue(ch[i]);
            }
        }
        else
        {
        System.out.println(s);
        }
        y=sum;      

    }while(ch.length>1);

}
Sumeet
  • 8,086
  • 3
  • 25
  • 45
2

I think your solution has wrong basics. There is no point to convert your number to String and handle this as char array. You are doing too much unnecessary operations.

You can do is simpler if you stick with numbers.

You can do it using recursion:

public static int sumRec(int number){
    if (number<10){
        return number;
    }
    int sum = 0;
    while(number!=0){
        sum += number %10;
        number /= 10;

    }
    return sumRec(sum);
}

or itteration

public static int sumIt(int number){
    while(number>=10){
        int sum = 0;
        while(number!=0){
            sum += number %10;
            number /= 10;
        }   
        number = sum;
    }
    return number;
}

it is much simpler, right?

user902383
  • 8,420
  • 8
  • 43
  • 63
  • I agree its much simpler but when you are solving the logic for the first time how wud u know that u need to divide/mod by 10?i am very bad at math:) – Akhil Maripally Aug 23 '15 at 10:15
2

You can solve this by 1 line:

public static int sumDigits(int n) {
    return (1 + ((n-1) % 9);   
  }

For example: input 777--> return 1 + ( (777-1) % 9) = 3

Also can work with negative number.

Twitter khuong291
  • 11,328
  • 15
  • 80
  • 116
1

Recursive variant

public static int myFunction(int num){
    if(num/10 == 0){
        return num;
    }

    int digitSum = num%10 + myFunction(num/10);

    if(digitSum/10 == 0){
        return digitSum;
    }

    return myFunction(digitSum);
} 
Tigran Babajanyan
  • 1,967
  • 1
  • 22
  • 41
0
public static int sum_of_digits(int n) {
    return --n % 9 + 1;
}