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.
Related
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);
}
}
}
I am having a hard time figuring out the solution to this problem. I need to write a program that gets an input n (via scanner), then goes with a for loop till that input number, checks if the numbers are divisible by 13 and then multiplies the digits of each number.
So for an example, if the input number is 40, the divisible numbers by 13 would be 13, 26, 39
1+3 = 4,
2+6 = 8,
3+9 = 12
so that's 4*8*12 = 384.
My current code, but I'm stuck here. I probably didn't do it right, too:
Scanner myScanner = new Scanner(System.in);
int num = myScanner.nextInt();
int sum = 0;
for (int i = 0; i < 30; i = i + 1) {
if (i % 13 == 0) {
while (i > 0) {
int add = i % 10;
sum = sum + add;
i = i / 10;
}
}
}
You're computing the sum of the digits, not the product. Also, you're loop is going to 30, not to num. (There's also no reason to start the loop at 0 instead of 1.) Finally, you shouldn't be changing i inside the loop itself; that will screw up the iteration logic. Use an auxiliary variable. Something like this (untested) should work:
Scanner myScanner = new Scanner(System.in);
int num = myScanner.nextInt();
int prod = 1;
for (int i = 1; i < num; i++) {
if (i % 13 == 0) {
int j = i,
sumOfDigits = 0;
while (j > 0) {
int digit = j % 10;
sumOfDigits += digit;
j /= 10;
}
prod *= sumOfDigits;
}
}
Your whole code is messy. You need to work more on loops and variable assignments and scopes.
Given below is the correct code.
Scanner myScanner = new Scanner(System.in);
int num = myScanner.nextInt();
int mul = 1;
for (int i = 1; i < num; i = i + 1) {
if (i % 13 == 0) {
int sum = 0;
int number = i; // = some int
while (number > 0) {
sum = sum + (number % 10);
number = number / 10;
}
mul = mul * sum;
}
}
System.out.println(mul);
myScanner.close();
Another way to do it, change the number that are divisible to char array, then add and multiply.
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number: ");
int num = sc.nextInt();
int prod = 1;
for (int i = 1; i < num; i++) {
if (i % 13 == 0) {
String number = String.valueOf(i);
char[] digits1 = number.toCharArray();
int sum = 0;
for (char ii:digits1) {
sum = Character.getNumericValue(ii) + sum;
}
prod = prod*sum;
}
}
System.out.println(prod);
I was writing a program to find armstrong numbers from 100 to 999. If I give number as an input program works but if I check number using while loop it says that every number not an armstrong number. I can't understand why.
That is the code:
package armstrong;
//import java.util.Scanner;
public class Armstrong {
public static void main(String[] args) {
int n, sum = 0, temp, remainder, digits = 0;
//Scanner in = new Scanner(System.in);
//System.out.println("Input a number to check if it is an Armstrong number");
//n = in.nextInt();
n = 100;
while (n <= 999) {
temp = n;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp / 10;
}
temp = n;
while (temp != 0) {
remainder = temp % 10;
sum = sum + power(remainder, digits);
temp = temp / 10;
}
if (n != sum) System.out.println(n + " is not an Armstrong number.");
else System.out.println("Armstrong number:" + n);
n++;
}
}
static int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p * n;
return p;
}
}
You should initialize digits, sum to zero in your loop like:
while (n <= 999) {
digits = 0;
sum = 0
...
}
Based on this page: http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/arms.html
You should set sum to back to zero inside the loop:
while(n <= 999) {
temp = n;
sum = 0;
...
}
and power method should be:
static int power(int n) {
return n * n * n;
}
Hope it helps.
The purpose of my code is to determine the number of times the number 3 appears between a range of numbers, the lower and upper bounds determined by the user.
So far, I can check if the number 3 is in the ten's place my using the modulus. But I am having trouble figuring out if a 3 resides in the hundreds, thousandths, etc. I know I need to use a nested loop, but I can't quite figure out how to code it.
Here is my code so far.
public class JavaThree {
public static void main (String [] args) {
int count = 0;
int num;
System.out.print("Enter lower end: ");
int lowerEnd = IO.readInt();
System.out.print("Enter upper end: ");
int upperEnd = IO.readInt();
if (lowerEnd > upperEnd) {
IO.reportBadInput();
return;
} else {
for(num = lowerEnd; num <= upperEnd; num++) {
if(num % 10 == 3) {
count = count + 1;
} else {
count = count;
}
}
}
IO.outputIntAnswer(count);
}
}
here is proper for loop for your task:
for(num = lowerEnd; num <= upperEnd; num++)
{
int nNum = num;
while (nNum > 0)
{
if( (nNum % 10) == 3)
count = count + 1;
nNum = nNum / 10;
}
}
Another solution, although not as efficient as the solution proposed #Ilya Bursov is to convert the number to a string and count the appearences of the char '3':
int threeCount = 0;
for (int num = lowerEnd; num < upperEnd; num++) {
String strNumber = String.valueOf(num);
for (int i = 0; i < strNumber.length(); i++) {
if (strNumber.charAt(i) == '3') {
threeCount++;
}
}
}
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.