I've been trying to sum a certain digit from a number, for example
Number: 5
Input: 54365
Output: The sum of 5's is 10
Second example:
Number: 5
Input: 5437555
Output: The sum of 5's is 20
I've managed to separate the digits yet I couldn't find the condition to sum
a certain number (for instance number 5 like the examples).
I'd appreciate to hear your idea of doing it
public static void main(String[] args) {
int sum = 0;
int number = MyConsole.readInt("Enter a number:");
while (number > 0) {
if (number % 10 == 8) {
sum += 8;
} else {
number /= 10;
}
}
System.out.println("The sum of 8's is:" + sum);
}
My way of separating the numbers.
Also i have a small program to get input instead of using scanner since we still haven't went through it in class.
Your requirement seems reasonably clear to me.
Given a number
final int number = 5;
And a starting number
final int input = 54365;
The easiest way is to convert that number to a String
final int inputStr = String.valueOf(input);
Then, you can filter each char for it, and sum them
final int sum =
inputStr.chars() // Get a Stream of ints, which represent the characters
.map(Character::getNumericValue) // Convert a char to its numeric representation
.filter(i -> i == number) // Filter for the designated number
.sum(); // Sum all the filtered integers
Output: 10
Using the same approach, but with an old-style for loop
final int input = 54365;
final int inputStr = String.valueOf(input);
final int number = 5;
int sum = 0;
for (final char c : inputStr.toCharArray()) {
final int n = Character.getNumericValue(c);
if (n == number) {
sum += number;
}
}
Your solution can work
int number = 5;
int input = 543655;
int sum = 0;
while (input > 0) {
if (input % 10 == number) {
sum += number;
}
input /= 10;
}
Related
I need to get from the user the length and the value of the array and return the digit that shows the most times. for example: the user gave me the length "4" and the numbers {83,238,8,54} the function will return " the numbers that shows the most times is 8";
but it send an error massage if the user enter more than 10 digits in general.
String sum = "";
// get the length
System.out.println("Enter the size of the array :");
int size = in.nextInt();
// create the array
String[] arr = new String[size+1];
// get value
System.out.println("Enter the elements of the array:(max capity 10 digits) ");
for(int i=0; i<arr.length; i++) {
arr[i] = in.nextLine();
sum+=arr[i];
}
System.out.println("the numbers that you gave me are: "+sum);
int all = Integer.parseInt(sum);
System.out.println("the digit that shows the most time is: "+maxOccurring(all));
}
static int countOccurrences(int x,int d) {
int count = 0;
while (x > 0)
{
if (x % 10 == d)
count++;
x = x / 10;
}
return count;
}
static int maxOccurring( int x)
{
if (x < 0)
x = -x;
int result = 0;
int max_count = 1;
for (int d = 0; d <= 10; d++)
{
int count = countOccurrences(x, d);
if (count >= max_count)
{
max_count = count;
result = d;
}
}
return result;
}
}
```
You get an NumberFormatException at the following line:
int all = Integer.parseInt(sum);
Exception trace is:
Exception in thread "main" java.lang.NumberFormatException: For input string: "25445648942"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at scan.ScannerTest.main(ScannerTest.java:27)
This exception is telling you that Integer.parseInt can't interpret the number you're passing through it (obtained by concatenating all the entered digits), in this precise example: "25445648942"
That's because this function is trying to yield an Integer from all those digits, which has a maximum capacity of 2^31 - 1 = 2,147,483,647. The entered number is higher that this, so it logically fails.
You should treat each entered number separately and count the digits in each, then do a sum of all to get your answer.
BTW, you don't ever need to convert to a number type to count the digits. It's simple string processing
This is my first time asking a question and I have tried to search the existing threads first. My program is meant to ask the user to enter a 5-digit number and it will check to see if it is a palindrome by reversing the number and then comparing the original number to the reverse. I also put in some verification steps there to reject the number if it is longer or shorter than 5 digits. Everything seems to work until it gets to the part comparing the original number and the reversed number. Here is my code:
import java.util.Scanner;
public class Palindromes {
public static void main(String args[]) {
int n, reverse = 0;
System.out.println("Enter a 5-digit integer to see if it is a palindrome.");
Scanner in = new Scanner(System.in);
n = in.nextInt();
int length = String.valueOf(n).length();
while (length > 5 || length < 5) {
System.out.println("Error: integer must be 5 digits in length.");
System.out.println("Enter a 5-digit integer.");
n = in.nextInt();
length = String.valueOf(n).length();
}
while (length == 5 && n != 0) {
reverse = reverse * 10;
reverse = reverse + n % 10;
n = n / 10;
}
System.out.println("Reversed number is: " + reverse);
if (n == reverse) {
System.out.println("Congratulations! Your number is a palindrome!");
} else {
System.out.println("Sorry. Your number isn't a palindrome.");
}
}
}
Look at what you are doing here!
while (length == 5 && n != 0) {
reverse = reverse * 10;
reverse = reverse + n % 10;
n = n / 10; // <----- You are changing "n"!
}
Which means that after the loop, n will no longer be the same n that the user entered.
To fix this, copy n to another variable and modify that instead.
int temp = n;
while (length == 5 && temp != 0) {
reverse = reverse * 10;
reverse = reverse + temp % 10;
temp = temp / 10;
}
it's more easy to convert the number to an array and reverse it instead of calculating it:
let reverseNumber = parseInt(12345.toString().split("").reverse().join());
I tried to write a simple java program which counts how many odd digits there are inside a number (for example, for input "123" the program should return 2). The program instead returns all the digits of the given number. Any idea?
import java.util.*;
//Counts the number of odd digits in an int using recursion
public class OddCount{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Digit a positive int number: ");
int n = in.nextInt();
System.out.println("The number of odd digits is " + oddDigitCounter(n));
}
public static int oddDigitCounter(int number) {
int result = 0;
if(number<=10){
if(number%2==0)
result = 0;
else
result++;
}
else{
if(number%10!=0){
if((number%10)/2!=0)
result = 1 + oddDigitCounter(number/10);
else
result = 0 + oddDigitCounter(number/10);
}
else{
result = 0 + oddDigitCounter(number/10);
}
}
return result;
}
}
Here is a way to write your recursive method without all the unnecessary conditions.
public static int oddDigitCounter(int number) {
if (number==0) {
return 0;
}
return (number&1) + oddDigitCounter(number/10);
}
Using &1 instead of %2 allows it to work for negative numbers as well as positive ones.1
1 (number&1) is zero for an even number, and one for an odd number, and works regardless of whether the number is positive or negative. For instance, if number==-3 then (number%2)==-1, but (number&1)==1, which is what we want in this case.
Check your code, you are using / instead of % in this if condition:
if((number%10)/2!=0)
It should be:
if((number%10)%2!=0)
In oddDigitCounter() why don't you simply check digit by digit if it's an even or odd one and echo (store) the result?
Recursive approach: at first call you may pass to the function the entire number and then if the number is 1 digit long let the function do the check and return, otherwhise do the check against the 1st digit and pass the others again to the function itself.
Procedural approach: do a simple loop through the digits and do the checks.
You can use following sample:
import java.util.Scanner;
public class NumberOfOddDigist {
private static int count = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Digit a positive int number: ");
int n = in.nextInt();
countOdd(n);
System.out.println("The number of odd digits is " + count);
in.close();
}
public static void countOdd(int number) {
int remainder = number % 10;
int quotient = (number - remainder) / 10;
if (!(remainder % 2 == 0)) {
count++;
}
number = quotient;
if (number < 10) {
if (!(number % 2 == 0)) {
count++;
}
} else {
countOdd(number);
}
}
}
I am trying to create a program that will tell if a number given to it is a "Happy Number" or not. Finding a happy number requires each digit in the number to be squared, and the result of each digit's square to be added together.
In Python, you could use something like this:
SQUARE[d] for d in str(n)
But I can't find how to iterate through each digit in a number in Java. As you can tell, I am new to it, and can't find an answer in the Java docs.
You can use a modulo 10 operation to get the rightmost number and then divide the number by 10 to get the next number.
long addSquaresOfDigits(int number) {
long result = 0;
int tmp = 0;
while(number > 0) {
tmp = number % 10;
result += tmp * tmp;
number /= 10;
}
return result;
}
You could also put it in a string and turn that into a char array and iterate through it doing something like Math.pow(charArray[i] - '0', 2.0);
Assuming the number is an integer to begin with:
int num = 56;
String strNum = "" + num;
int strLength = strNum.length();
int sum = 0;
for (int i = 0; i < strLength; ++i) {
int digit = Integer.parseInt(strNum.charAt(i));
sum += (digit * digit);
}
I wondered which method would be quickest to split up a positive number into its digits in Java, String vs modulo
public static ArrayList<Integer> splitViaString(long number) {
ArrayList<Integer> result = new ArrayList<>();
String s = Long.toString(number);
for (int i = 0; i < s.length(); i++) {
result.add(s.charAt(i) - '0');
}
return result; // MSD at start of list
}
vs
public static ArrayList<Integer> splitViaModulo(long number) {
ArrayList<Integer> result = new ArrayList<>();
while (number > 0) {
int digit = (int) (number % 10);
result.add(digit);
number /= 10;
}
return result; // LSD at start of list
}
Testing each method by passing Long.MAX_VALUE 10,000,000 times, the string version took 2.090 seconds and the modulo version 2.334 seconds. (Oracle Java 8 on 64bit Ubuntu running in Eclipse Neon)
So not a lot in it really, but I was a bit surprised that String was faster
In the above example we can use:
int digit = Character.getNumericValue(strNum.charAt(i));
instead of
int digit = Integer.parseInt(strNum.charAt(i));
You can turn the integer into a string and iterate through each char in the string. As you do that turn that char into an integer
This code returns the first number (after 1) that fits your description.
public static void main(String[] args) {
int i=2;
// starting the search at 2, since 1 is also a happy number
while(true) {
int sum=0;
for(char ch:(i+"").toCharArray()) { // casting to string and looping through the characters.
int j=Character.getNumericValue(ch);
// getting the numeric value of the current char.
sum+=Math.pow(j, j);
// adding the current digit raised to the power of itself to the sum.
}
if(sum==i) {
// if the sum is equal to the initial number
// we have found a number that fits and exit.
System.out.println("found: "+i);
break;
}
// otherwise we keep on searching
i++;
}
}
I'm trying to count trailing zeros of numbers that are resulted from factorials (meaning that the numbers get quite large). Following code takes a number, compute the factorial of the number, and count the trailing zeros. However, when the number is about as large as 25!, numZeros don't work.
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
double fact;
int answer;
try {
int number = Integer.parseInt(br.readLine());
fact = factorial(number);
answer = numZeros(fact);
}
catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static double factorial (int num) {
double total = 1;
for (int i = 1; i <= num; i++) {
total *= i;
}
return total;
}
public static int numZeros (double num) {
int count = 0;
int last = 0;
while (last == 0) {
last = (int) (num % 10);
num = num / 10;
count++;
}
return count-1;
}
I am not worrying about the efficiency of this code, and I know that there are multiple ways to make the efficiency of this code BETTER. What I'm trying to figure out is why the counting trailing zeros of numbers that are greater than 25! is not working.
Any ideas?
Your task is not to compute the factorial but the number of zeroes. A good solution uses the formula from http://en.wikipedia.org/wiki/Trailing_zeros (which you can try to prove)
def zeroes(n):
i = 1
result = 0
while n >= i:
i *= 5
result += n/i # (taking floor, just like Python or Java does)
return result
Hope you can translate this to Java. This simply computes [n / 5] + [n / 25] + [n / 125] + [n / 625] + ... and stops when the divisor gets larger than n.
DON'T use BigIntegers. This is a bozosort. Such solutions require seconds of time for large numbers.
You only really need to know how many 2s and 5s there are in the product. If you're counting trailing zeroes, then you're actually counting "How many times does ten divide this number?". if you represent n! as q*(2^a)*(5^b) where q is not divisible by 2 or 5. Then just taking the minimum of a and b in the second expression will give you how many times 10 divides the number. Actually doing the multiplication is overkill.
Edit: Counting the twos is also overkill, so you only really need the fives.
And for some python, I think this should work:
def countFives(n):
fives = 0
m = 5
while m <= n:
fives = fives + (n/m)
m = m*5
return fives
The double type has limited precision, so if the numbers you are working with get too big the double will be only an approximation. To work around this you can use something like BigInteger to make it work for arbitrarily large integers.
You can use a DecimalFormat to format big numbers. If you format your number this way you get the number in scientific notation then every number will be like 1.4567E7 this will make your work much easier. Because the number after the E - the number of characters behind the . are the number of trailing zeros I think.
I don't know if this is the exact pattern needed. You can see how to form the patterns here
DecimalFormat formater = new DecimalFormat("0.###E0");
My 2 cents: avoid to work with double since they are error-prone. A better datatype in this case is BigInteger, and here there is a small method that will help you:
public class CountTrailingZeroes {
public int countTrailingZeroes(double number) {
return countTrailingZeroes(String.format("%.0f", number));
}
public int countTrailingZeroes(String number) {
int c = 0;
int i = number.length() - 1;
while (number.charAt(i) == '0') {
i--;
c++;
}
return c;
}
#Test
public void $128() {
assertEquals(0, countTrailingZeroes("128"));
}
#Test
public void $120() {
assertEquals(1, countTrailingZeroes("120"));
}
#Test
public void $1200() {
assertEquals(2, countTrailingZeroes("1200"));
}
#Test
public void $12000() {
assertEquals(3, countTrailingZeroes("12000"));
}
#Test
public void $120000() {
assertEquals(4, countTrailingZeroes("120000"));
}
#Test
public void $102350000() {
assertEquals(4, countTrailingZeroes("102350000"));
}
#Test
public void $1023500000() {
assertEquals(5, countTrailingZeroes(1023500000.0));
}
}
This is how I made it, but with bigger > 25 factorial the long capacity is not enough and should be used the class Biginteger, with witch I am not familiar yet:)
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.print("Please enter a number : ");
long number = in.nextLong();
long numFactorial = 1;
for(long i = 1; i <= number; i++) {
numFactorial *= i;
}
long result = 0;
int divider = 5;
for( divider =5; (numFactorial % divider) == 0; divider*=5) {
result += 1;
}
System.out.println("Factorial of n is: " + numFactorial);
System.out.println("The number contains " + result + " zeroes at its end.");
in.close();
}
}
The best with logarithmic time complexity is the following:
public int trailingZeroes(int n) {
if (n < 0)
return -1;
int count = 0;
for (long i = 5; n / i >= 1; i *= 5) {
count += n / i;
}
return count;
}
shamelessly copied from http://www.programcreek.com/2014/04/leetcode-factorial-trailing-zeroes-java/
I had the same issue to solve in Javascript, and I solved it like:
var number = 1000010000;
var str = (number + '').split(''); //convert to string
var i = str.length - 1; // start from the right side of the array
var count = 0; //var where to leave result
for (;i>0 && str[i] === '0';i--){
count++;
}
console.log(count) // console shows 4
This solution gives you the number of trailing zeros.
var number = 1000010000;
var str = (number + '').split(''); //convert to string
var i = str.length - 1; // start from the right side of the array
var count = 0; //var where to leave result
for (;i>0 && str[i] === '0';i--){
count++;
}
console.log(count)
Java's doubles max out at a bit over 9 * 10 ^ 18 where as 25! is 1.5 * 10 ^ 25. If you want to be able to have factorials that high you might want to use BigInteger (similar to BigDecimal but doesn't do decimals).
I wrote this up real quick, I think it solves your problem accurately. I used the BigInteger class to avoid that cast from double to integer, which could be causing you problems. I tested it on several large numbers over 25, such as 101, which accurately returned 24 zeros.
The idea behind the method is that if you take 25! then the first calculation is 25 * 24 = 600, so you can knock two zeros off immediately and then do 6 * 23 = 138. So it calculates the factorial removing zeros as it goes.
public static int count(int number) {
final BigInteger zero = new BigInteger("0");
final BigInteger ten = new BigInteger("10");
int zeroCount = 0;
BigInteger mult = new BigInteger("1");
while (number > 0) {
mult = mult.multiply(new BigInteger(Integer.toString(number)));
while (mult.mod(ten).compareTo(zero) == 0){
mult = mult.divide(ten);
zeroCount += 1;
}
number -= 1;
}
return zeroCount;
}
Since you said you don't care about run time at all (not that my first was particularly efficient, just slightly more so) this one just does the factorial and then counts the zeros, so it's cenceptually simpler:
public static BigInteger factorial(int number) {
BigInteger ans = new BigInteger("1");
while (number > 0) {
ans = ans.multiply(new BigInteger(Integer.toString(number)));
number -= 1;
}
return ans;
}
public static int countZeros(int number) {
final BigInteger zero = new BigInteger("0");
final BigInteger ten = new BigInteger("10");
BigInteger fact = factorial(number);
int zeroCount = 0;
while (fact.mod(ten).compareTo(zero) == 0){
fact = fact.divide(ten);
zeroCount += 1;
}
}