Byang is learning how to add numbers. However, he gets confused whenever there is a carry. To help B…
Click here to read the complete problem statement.
If you need help solving this problem, mention your approach and ask specific questions. Please avoid sharing your code and asking the Community to figure out “what’s wrong”.
However, I think that you are making it too complicated. My solution in Java is:
import java.util.*;
public class solution {
public static void main(String[] args) {
//scanner
Scanner sc = new Scanner(System.in);
//inputs
String a = sc.next();
String b = sc.next();
//calculations
boolean v = false;
int x;
int la = a.length();
int lb = b.length();
int min = Math.min(la, lb);
//loop
for (int i = 1; i <= min; ++i) {
x = Character.getNumericValue( a.charAt(la-i) ) + Character.getNumericValue( b.charAt(lb-i) );
if (x > 9) {
v = true;
break;
}
}
//results
if (v) System.out.println("Yes");
else System.out.println("No");
}
}
Your code produce wrong answer for input value 1238 7 is should print YES but it is printing NO
Let’s see why you’re getting wrong answer.
In your code for this input value x = 4 and y = 3. Then you’re starting the loop from y which is equal to 3. then you’re checking the third position of d which is empty because string d = "7" which means that d[0] = '7' and d[3] = ' ' so when you’re adding c[3]+d[3] that can give you random value like -60 so, that will never become bigger than 10 and count will not increase and you will get wrong answer.
The correct approach to this problem is first reverse the two string.
this way reverse(c.begin(), c.end()
and for the second string reverse(c.begin(), c.end()
then run the loop from 0 to min(c.length(), d.length())
I hope this will work. Let us know if there is any problem.