print number having digit 3 or 6 from 1 to 1000.like 3 ,6,13,16…996,

The name of the picture


print number having digit 3 or 6 from 1 to 1000.like 3 ,6,13,16…996,



Here is my code. When the value of the number is less than 100, output is correct but when the value of number is 1000.output is wrong


import java.util.*;
public class Test {
public static void main(String args) {
int i,x,y,z,num;
int number=1;

for(;number<1000;number++) {
i=number;
while (i > 0) {
z=i%10; //System.out.println( "digit="+z);
if(((z%3==0)&&(z%9!=0)&&(z!=0))||(z%6==0)&&(z!=0)) //condition for divisiblity by 3 or 6 and not by 9
{
System.out.println( "number="+number);
break;
}
i = i / 10;
}
}
}
}





because your loop is till 999 only
– Aman Chhabra
27 mins ago





I guess your if condition can be simplified to z==3 || z==6
– Luiggi Mendoza
23 mins ago


if


z==3 || z==6





No, 9 is divisible by 3
– sachin sarwesh
21 mins ago




2 Answers
2



This is much shorter and makes a whole lot more sense.


for(int i = 0; i < 1000; i++){
String str = Integer.toString(i);

for(int j = 0; j < str.length(); j++){
if(str.charAt(j) == '3' || str.charAt(j) == '6')
System.out.println("nuber = "+ i);
}
}





String.contains will do the task :)
– мυѕτавєւмo
29 secs ago


String.contains





it prints the numbers from 513 ,516 .....996
– sachin sarwesh
4 secs ago



Your code works just fine, the only thing missing is your loop is till 999.



Aslo, In Java 8, you can simply do :


IntStream.range(1,1001).mapToObj(p->Integer.toString(p)).filter(p->p.contains("3")||p.contains("6")).forEach(System.out::println);



Output:


3
6
13
16
.
.
993
996






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Stripe::AuthenticationError No API key provided. Set your API key using “Stripe.api_key = ”

CRM reporting Extension - SSRS instance is blank

Keycloak server returning user_not_found error when user is already imported with LDAP