Read an integer variable and print it in which the digits are separated into groups of three by comm…
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”.
My program is keep returning wrong answer in the last test(6). What should I do? Where is my problem? Here is My CODE(Java JDK 11.22)
import java.util.Scanner;
public class toph {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int num = s.nextInt();
String str = "";
int i = 1;
if(num ==0 || num == 200000000){
System.out.println(num);
}
if (0 <= num && num < 200000000) {
while (num != 0) {
str = num % 10 + "" + str;
num = num / 10;
if (i % 3 == 0 && num != 0) {
str = "," + str;
}
i++;
}
System.out.println(str);
}
}
First of all, this part of the condition seems odd:
(strn[0] != ch)
Since this is how you initialized ch:
char ch = '0';
This condition is comparing strn[0] for the digit 0, not the null character.
Next, you are going from left to right to add comma. Although that is technically possible, I don’t see the math in your code required to do that. The use of x and count seems a bit convoluted.
Can you explain what your thought process was behind this code? May be I can then help you simplify that and as a result you will be able to write a simpler solution for this problem.
Sorry for the late reply.
First of all I wrote that char ch = ‘0’ and I was not expecting a null character(/0).I know my logic is a little unclear to the readers. But what I meant is, if the first character in the input is 0 then don’t add a comma after that(since I misleadingly thaught the commas go from left to right).I added the x as 0 and changed to 2 because I wanted it to ignore that if() fafte adding the first comma