count all numbers in range having a specific digit - java

I want to count how many numbers have digit number 4 in a range of numbers
e.g 1-100 count all numbers having digit number
i.e 4,14,24,34,40,41,42,43,44,45,46,47,48,49,54,64,74,84 and 94 total 19 numbers
I am having problems with counting number of integers with digit 4 in them please help!!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int count = 0;
while (true) {
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt();
if (num1 != 0 || num2 != 0) {
for (int num = num1; num <= num2; num++) {
while (num != 0) {
int i = num % 10;
if (i == 4) {
count++;
break;
}
num = num / 10;
}
}
System.out.println(count);
}
else
break;
}
}
}

To check if a number contains a specific digit or not, here is a trick you can use :
Convert both number and digit to String and use String::contains (Simple)
Here is a piece of code you can use If you are using Java 8 :
int number = 4, min = 0, max = 100;
String numberToString = String.valueOf(number);
long count = IntStream.rangeClosed(min, max) //Range of numbers between min and max
.filter(n -> String.valueOf(n).contains(numberToString)) // Use the filter
.count();// Then count the result
System.out.println(count); // 19

//a few changes were needed into your code.. here is the solution...
public class MaxOccurance {
public static void main(String[] args) {
int count = 0;
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt(), temp;
if (num1 != 0 || num2 != 0) {
for (int num = num1; num <= num2; num++) {
temp = num;
while (temp != 0) {
int i = temp % 10;
if (i == 4) {
count++;
// break;
}
temp = temp / 10;
}
}
System.out.println(count);
}
}
}

Related

if condition is not working.when i try to execute if conditon,else is working

what's wrong with this?
if condition is not executing.
import java.util.Scanner;
public class ArmstrongNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("ENTER THE NUMBER");
int n = sc.nextInt();
int temp = n;
int rem = 0;
int sum = 0;
while (n != 0) {
rem = n % 10;
sum = sum + (rem * rem * rem);
n = n / 10;
}
if (temp == n) {
System.out.println("number is a AMSTRONG");
} else {
System.out.println("NUMBER IS NOT AMSTRONG");
}
}
}
Your logic is wrong. if(temp==n) { is after while(n!=0) { so the only way it could be true is if temp == 0.
Your Calcualtion is fine but your compare is wrong. For example the number 153, which is a armstrong number, your variables will have the following values at the end of the loop:
temp = 153
rem = 1
sum = 153
n = 0
So you should not compare temp to n temp == n , how you currently do but temp to sum temp == sum
Also take in mind that your check will only work for three digits numbers, because your power is allways three. So for other armstrong numbers it simply won't work, for example:
54748 = 55 + 45 + 75 + 45 + 85 = 3125 + 1024 + 16807 + 1024 + 32768
In this solution i used the Math libary and the power but there are more ways if you don't like this to calc the length of an number
public class ArmstrongNum {
private static final Scanner SC = new Scanner(System.in);
private static boolean isArmstrongNumber(int n){
int temp = n;
int rem;
int length = (int) (Math.log10(n) + 1);
int sum = 0;
while (n != 0) {
rem = n % 10;
sum = sum + (int) Math.pow(rem, length);
n = n / 10;
}
return temp == sum;
}
public static void main(String[] args) {
System.out.print("ENTER THE NUMBER: ");
int n = SC.nextInt();
if (isArmstrongNumber(n)) {
System.out.printf("%d is a Armstrong number", n);
} else {
System.out.printf("%d is no Armstrong number", n);
}
}
}
Try another way
public static void main(String[] args) {
try {
Scanner sc= new Scanner(System.in);
System.out.println("ENTER THE NUMBER");
int n = sc.nextInt();
if (n == 0) {
throw new Exception("Number is 0");
}
int sum = 0;
String number = String.valueOf(n);
char[] chars = number.toCharArray();
double length = chars.length;
for (char item : chars) {
double result = Math.pow(Double.parseDouble(String.valueOf(item)), length);
sum = sum + (int) result;
}
if (sum == n ) {
System.out.println("number is a AMSTRONG");}
else {
System.out.println("NUMBER IS NOT AMSTRONG");
}
} catch (Exception exception) {
System.out.println(exception.getMessage());
}
}

How to let the scanner stop receiving input?

I am trying to get the sum of the prime digit of an integer, but I cannot stop the scanner from getting input.
Here are my codes.
import java.util.Scanner;
public class Exercise {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
int a = input.nextInt();
System.out.println(Sum(a));
input.close();
}
public static int Sum(int a) {
int sum = 0;
int remainder;
int remainder2;
while (a >= 0) {
remainder = a % 10;
int prime = Prime(remainder);
sum += prime;
a = a / 10;
}
return sum;
}
public static int Prime(int remainder) {
int m = remainder / 2;
int flag = 0;
if (remainder != 0 && remainder != 1 && remainder != 2) {
for (int i = 2; i <= remainder / 2; i++) {
if (remainder % i == 0) {
flag = 1;
break;
}
}
}
if (flag == 1) {
remainder = 0;
}
return remainder;
}
}
It seems your program is going in an infinite loop before input.close(); is called.
change the while to stop at >0
while (a > 0)
and try again.

How to sum the digits of two integers?

How could I use the following method to sum the integers of two numbers in a separate method? I'm trying to teach myself how to use overloaded methods but this is starting to confuse me. Thanks!
public static void sumNUmber(){
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int sum = 0;
while (num > 0) {
sum = sum + num % 10;
num = num / 10;
}
System.out.println(sum);
public static void main(String[] args) throws ClassNotFoundException {
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
System.out.println(sumDigits(num));
}
public static int sumDigits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num = num / 10;
}
return sum;
}
output
Enter a number
234
9
You probably want to take your core algorithm and put it into a single function and then call it twice, once for each number. For example,
// Core algorithm.
public static int sumDigits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num = num / 10;
}
return sum;
}
public static void sumNumber() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
int numA = in.nextInt();
System.out.println("Enter another number");
int numB = in.nextInt();
int totalDigits = sumDigits(numA) + sumDigits(numB);
System.out.println(totalDigits);
}
//Merry Xmas :D
public int sumNumbers(int num) {
int returnval;
if (num < 10) {
return num;
} else if (num < 100) {
returnval = Math.floor(num/10) + (num%10);
} else if (num < 1000) {
returnval = Math.floor(num/100) + Math.floor(num/10) + (num%10);
} //repeat as needed
return 0;
}

Debugging for loop in palindrome numbers code

This code gets an integer n and displays all palindrome numbers less than n.
But seems the for loop doesn't work; because when I enter a number except 0, 1 and negatives, nothing happens.
I tried debugging, but couldn't find the problem!
Sample input: 30
Sample output: 1 2 3 4 5 6 7 8 9 11 22
import java.util.Scanner;
public class PalindromeNumbers {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
if (n == 0 || n == 1 || n < 0)
System.out.println("There's no Palindrome Number!");
else {
for (int num = 1; num < n; num++) {
int reversedNum = 0;
int temp = 0;
while (num > 0) {
// use modulus operator to strip off the last digit
temp = num % 10;
// create the reversed number
reversedNum = reversedNum * 10 + temp;
num = num / 10;
}
if (reversedNum == num)
System.out.println(num);
}
}
}
}
You run into an infinite loop: you use num in your for loop as an index, and reset it to 0 inside the loop. Use different variables, and it should work!
for (int i = 1; i < n; i++) {
int num = i;
...
if (reversedNum == i)
System.out.println(i);
}
You can do it in a more concise way:
public static void main(final String args[]) {
final Scanner input = new Scanner(System.in);
final int max = input.nextInt();
if (max <= 0) {
System.out.println("There's no Palindrome Number!");
} else {
for (int i = 1; i < max; i++) {
if (isPalindrome(i)) {
System.out.println(i);
}
}
}
}
private static boolean isPalindrome(final int num) {
final String temp = "" + num;
return new StringBuilder(temp).reverse().toString().equals(temp);
}
You are changing your num variable inside your for loop. The next time num < n is executed, the value changed (to 0). Try something like this:
for (int num = 1; num < n; num++) {
int reversedNum = 0;
int temp = 0;
int temp2 = num;
while (temp2 > 0) {
// use modulus operator to strip off the last digit
temp = temp2 % 10;
// create the reversed number
reversedNum = reversedNum * 10 + temp;
temp2 = temp2 / 10;
}
if (reversedNum == num)
System.out.println(num);
}
This way, you use a temp variable to calculate your reversedNum, and still keeps the value of num for the next loop iteration.

Count of most occurring digit... Find the digit that occurs most in a given number

the following s the code to
Find the number of occurrences of a given digit in a number.wat shall i do in order to Find the digit that occurs most in a given number.(should i create array and save those values and then compare)
can anyone please help me ..
import java.util.*;
public class NumOccurenceDigit
{
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
System.out.println("Enter a Valid Digit.(contaioning only numerals)");
int number = s.nextInt();
String numberStr = Integer.toString(number);
int numLength = numberStr.length();
System.out.println("Enter numer to find its occurence");
int noToFindOccurance = s.nextInt();
String noToFindOccuranceStr = Integer.toString(noToFindOccurance);
char noToFindOccuranceChar=noToFindOccuranceStr.charAt(0);
int count = 0;
char firstChar = 0;
int i = numLength-1;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
static void recFunNumOccurenceDigit(char firstChar,int count,int i,char noToFindOccuranceChar,String numberStr)
{
if(i >= 0)
{
firstChar = numberStr.charAt(i);
if(firstChar == noToFindOccuranceChar)
//if(a.compareTo(noToFindOccuranceStr) == 0)
{
count++;
}
i--;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
else
{
System.out.println("The number of occurance of the "+noToFindOccuranceChar+" is :"+count);
System.exit(0);
}
}
}
/*
* Enter a Valid Digit.(contaioning only numerals)
456456
Enter numer to find its occurence
4
The number of occurance of the 4 is :2*/
O(n)
keep int digits[] = new int[10];
every time encounter with digit i increase value of digits[i]++
the return the max of digits array and its index. that's all.
Here is my Java code:
public static int countMaxOccurence(String s) {
int digits[] = new int[10];
for (int i = 0; i < s.length(); i++) {
int j = s.charAt(i) - 48;
digits[j]++;
}
int digit = 0;
int count = digits[0];
for (int i = 1; i < 10; i++) {
if (digits[i] > count) {
count = digits[i];
digit = i;
}
}
System.out.println("digit = " + digit + " count= " + count);
return digit;
}
and here are some tests
System.out.println(countMaxOccurence("12365444433212"));
System.out.println(countMaxOccurence("1111111"));
declare a count[] array
and change your find function to something like
//for (i = 1 to n)
{
count[numberStr.charAt(i)]++;
}
then find the largest item in count[]
public class Demo{
public static void main(String[] args) {
System.out.println("Result: " + maxOccurDigit(327277));
}
public static int maxOccurDigit(int n) {
int maxCount = 0;
int maxNumber = 0;
if (n < 0) {
n = n * (-1);
}
for (int i = 0; i <= 9; i++) {
int num = n;
int count = 0;
while (num > 0) {
if (num % 10 == i) {
count++;
}
num = num / 10;
}
if (count > maxCount) {
maxCount = count;
maxNumber = i;
} else if (count == maxCount) {
maxNumber = -1;
}
}
return maxNumber;
}}
The above code returns the digit that occur the most in a given number. If there is no such digit, it will return -1 (i.e.if there are 2 or more digits that occurs same number of times then -1 is returned. For e.g. if 323277 is passed then result is -1). Also if a number with single digit is passed then number itself is returned back. For e.g. if number 5 is passed then result is 5.

Categories