Monday, 18 June 2012

Program for printing numbers from 1 to 100, which contains digit 5?

public class PrintNumbers
{
    public static void main(String[] args) {
        for (int i = 0; i <= 100; i++) {
            if (isContainGivenNo(i, 5)) {
                System.out.println(i);
            }
        }
    }

    private static boolean isContainGivenNo(int no, int containNo) {
        while (no > 9) {
            int remainder = no % 10;
            if (remainder == containNo) {
                return true;
            }
            no /= 10;
        }
        return no == containNo;
    }
}
(or)
public class PrintNumbers
{
    public static void main(String[] args){
        for(int i = 1; i < 100; i++){
            String s = ""+i;
            if (s.contains("5")){
                System.out.println(i);
            }
        }
    }
}
Output : 5 15 25 35 45 51 52 53 54 55 56 57 58 59 65 75 85 95

No comments:

Post a Comment