Question about adding three digits with each other in java [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a task to add each numbers. One of my colleague helped me out and here's the code.
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number%10;
number = number/10;
sum = sum + number%10;
number = number/10;
sum = sum + number%10;
number = number/10;
return sum;//write your code here
}
I'm not sure exactly how this works. Can someone please explain to me? Thanks.

You can use within while the loop which will accept any number as #GBlodgett suggested
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
while(number!=0)
{
sum = sum + number%10;
number = number/10;
}
return sum;//write your code here
}

In Java % is the modulo operator. It delivers the remainder of that division. If you divide integer values in Java, any remainder will be lost.
If you add some makeshift logging like that:
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
return sum; // write your code here
you will get the following output:
54
5
0
15
546 % 10 = 6
546 / 10 = 54
54 % 10 = 4
54 / 10 = 5
5 % 10 = 5
5 / 10 = 0
sum = 6 + 5 + 4 = 15
Your code will only work up to three digits. If you transfer the sequence of modulo and division operations into a loop it will be a generic solution.

The JVM(Java Virtual Machine) starts executing your code and public static void
main(String[] args) is the starting point.
Then executes System.out.println(sumDigitsInNumber(546));
System.out.println() is a method that prints the argument passed, into the System.out which is generally stdout (Standard output). The argument passed is the sumDigitsInNumber(546) method, hence it would print what sumDigitsInNumber() would return.
sumDigitsInNumber() initializes a sum variable with 0 to store the sum of 546.
sum = sum + number%10 gives you 6 (0 + 6), where number%10 gives
the last digit of 546 which is 6
number = number / 10 will replace number by 54 because 546/10 is 54.6 since it is an integer division .6 is ignored and 54 is stored in the number.
Repeat the above step twice but the number being 54 and then 5.
return sum returns the sum to the caller which is your main() method, hence System.out.println() printing the sum of 546.

Step by step:
this creates variable named sum and assigns it value of 0:
int sum = 0;
this does the following:
it assigns to variable 'sum' the result of sum + number % 10 (where a number is an argument passed to the method)
sum = sum + number%10;
number % 10 is in your example a remainder of 456 / 10, so in 456, you can pack number 10 exactly 45 times, whatever is left that is less then 10 is your result (remainder), in this case 6.
see http://www.cafeaulait.org/course/week2/15.html
next we divide current number by 10:
number = number / 10;
so 456 / 10 = 45.6
and as the type of variable is int - it is actually 45 (as int always rounds down the remainder) - see Int division: Why is the result of 1/3 == 0?
then it is being repeated 2 times until all 3 digits are summed up.
Notice, that your method will only work for 3 digit numbers. That's not that good.
You can easily make your method to work with any digits length int number passed.
Hint: use loops!
As you can see, you're repeating the same piece of code 3 times.
You could place it inside a loop and make it execute as many times as there are digits in your number.
something along these lines, but you need to figure out when to stop the while loop!
int sum = 0;
while (?WHEN TO EXIT?) {
sum = sum + number % 10;
number = number / 10;
}
Think about when you can exit loop (when, in example, maybe this number variable that you divide by 10 each iteration can tell you that all digits have been processed?)

Here is a solution that computes the sum of a number, no matter how many digits it has:
Generally speaking, a number has exactly [log(number)+1] digits, the tempInt variable is introduced to store the parameter value, it is considered a bad practice to modify the values of the method parameters :
public static int sumOfDigits(int number) {
int sum = 0;
int length = (int) Math.ceil(Math.log10(number));
int tempInt = number;
for (int i = 0; i < length; i++) {
sum += tempInt % 10;
tempInt /= 10;
}
return sum;
}

public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number%10; // number%10 = the last digit of 546 (= 6), sum = 0 + 6
number = number/10; // number = number whithout the last digit (54)
sum = sum + number%10; // number%10 = the last digit of 54 (= 4), sum = 0 + 6 + 4
number = number/10; // number = number whithout the last digit (5)
sum = sum + number%10; // number%10= the last digit of 5 (= 5), sum = 0 + 6 + 4 + 5
number = number/10; // number = number whithout the last digit (useless)
return sum;//sum = 6 + 5 + 4 = 15
}

Related

How does this program to calculate Armstrong numbers between two intervals work step by step?

class Armstrong {
public static void main(String[] args) {
int low = 999, high = 99999;
for(int number = low + 1; number < high; ++number) {
int digits = 0;
int result = 0;
int originalNumber = number;
// number of digits calculation
while (originalNumber != 0) {
originalNumber /= 10;
++digits;
}
originalNumber = number;
// result contains sum of nth power of its digits
while (originalNumber != 0) {
int remainder = originalNumber % 10;
result += Math.pow(remainder, digits);
originalNumber /= 10;
}
if (result == number)
System.out.print(number + " ");
}
}
How does this program work? It would be very helpful. Program to find Armstrong between two intervals? Can someone explain step by step? Help me out.
Steb-by-step Explanantion
Initialize the start and end of the interval with 999 and 9999
You can change these numbers but ensure that low is always lesser than high:
int low = 999;
int high = 99999;
for (int number = low + 1; // Create a variable number and assign it one number greater than low
number < high; // This loop should keep repeating until number is less than high(end of the interval)
++number // After each repetition, increment the value of number by 1
) {
Create a variable digits to store the number of digits in number.
For example, if number is 100, this will be later set as 3 as the algorithm proceeds:
int digits = 0;
Create a variable result that will store the sum of powers of numbers:
int result = 0;
Copy the value of number to a local variable originalNumber because it has to be modified:
int originalNumber = number;
The logic of calculating number of digits in a number is keep dividing it by 10 until the number is 0.
Every time you divide any number by 10, the last digit is stripped out. So every time the last digit is stripped out, increment digit by 1 (digit++)
// number of digits calculation
while (originalNumber != 0) // Continue this while loop till originalNumber is not 0
{
originalNumber /= 10; // Divide the number by 10. Dividing a number by 10 removes its last digit.
++digits; // One digit was removed in the above step, which means it has to be counted, so increment digit by 1
}
// For example, for originalNumber = 423,
// 423 / 10 = 42 : digits = 1 (first loop)
// 42 / 10 = 4 : digits = 2 (second loop)
// 4 / 10 = 0 : digits = 3 (third loop)
// Now originalNumber has become 0, so the while loop condition originalNumber != 0 will be false and the loop will stop.
// Now we have digits = 3, which is the number of digits in 423
// When program reaches here, digits will have the number of digits in the
// number "originalNumber"
Copy number again to originalNumber because we want to modify the number
again and originalNumber has become 0 because of the digit counting loop above:
originalNumber = number;
An Armstrong number is a number which is equal to the sum of digits to the power of its number of digits.
e.g.: in 153, (1^3) + (5^3) + (3^3) = 153. We are obtaining the cube of each digit(1, 5, 3) because 153 has 3 digits 1, 5, 3.
If it was say 50, we would check ( 5^2 + 0^2) because 50 has 2 digits (50 is not Armstrong, because 25 + 0 = 25 which is not equal to 50)
We saw above dividing a number by 10 removes the last digit (423 / 10 = 42)
Similarly, if we only want this last digit, we can get it by modulus 10 (% 10): (423 % 10 = 3) (42 % 10 = 2) (4 % 10 = 4)
// Let's assume originalNumber is 153
while (originalNumber != 0) // Same as above, keep looping till the originalNumber is not 0(i.e. all digits have been removed)
{
Extract the last digit to remainder, (for 153: 153 % 10 = 3) (for 15: 15 % 10 = 5)
int remainder = originalNumber % 10;
Now we have the last digit, we need to raise this digit to the number of
digits i.e. 3(for 153): (3^3) = 27. We do this using Math.pow(3, 3). Add this number to result. In the end after each loop's number's power is added, at the end of the loop, result will contain their sum:
result += Math.pow(remainder, digits);
originalNumber /= 10; // Remove the last digit (same as above, for 153: 153 / 10 = 15)
// After this line finishes, one rightmost digit will be removed, this will keep
// happening till originalNumber = 153 becomes 15, then 1, then 0.
// When originalNumber is 0, loop stops and we will have the total sum in result
}
For an Armstrong number like 153, result will also contain 153. For a non-Armstrong number it will contain something else.
if (result == number) // For 153, both will be equal.
System.out.print(number + " "); // This will only execute if result is equal to number, or in other words, only if the number is Armstrong
}
Improvements
As per single responsibility principle, each function or class must exactly do one thing. You have a monolithic main() method that:
Defines the interval
Counts the digit of each number in the interval
Calculate the sum of powers of digits
Check if number is Armstrong and print it.
I would prefer breaking down each operation to a separate method, so that it improves readability and maintainability while respecting single-responsibiliy principle:
class Armstrong {
public static int countDigits(int number) {
int digits = 0;
while (number != 0) {
number /= 10;
++digits;
}
return digits;
}
public static int digitPowerSum(int number, int power) {
int result = 0;
while (number != 0) {
int remainder = number % 10;
result += Math.pow(remainder, power);
number /= 10;
}
return result;
}
public static boolean isArmstrong(int number) {
int digits = countDigits(number);
int sum = digitPowerSum(number, digits);
return sum == number ; // will return true if both numbers are equal else false
}
public static ArrayList<Integer> armstrongNumbersBetween(int low, int high) {
ArrayList<Integer> numbers = new ArrayList<>();
for(int number = low + 1; number < high; number++) {
if (isArmstrong(number)) {
numbers.add(number);
}
}
return numbers;
}
public static void main(String[] args) {
int low = 999, high = 99999;
ArrayList<Integer> numbers = armstrongNumbersBetween(low, high);
for(int number : numbers) {
System.out.print(number + " ");
}
}
}
Here, each method does exactly one thing and this helps in better reusability. You just have to call the required methods to perform a specific operation.
If something is unclear, let me know.

Java Split Number into Digit's Algorithm

package test;
import java.util.Scanner;
public class SplitNumber
{
public static void main(String[] args)
{
int num, temp, factor = 1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
num = sc.nextInt();
temp = num;
while (temp != 0) {
temp = temp / 10;
factor = factor * 10;
}
System.out.print("Each digits of given number are: ");
while (factor > 1) {
factor = factor / 10;
System.out.print((num / factor) + " ");
num = num % factor;
}
}
}
I can't understand this int factor's job. Can someone help me to understand this codes algorithm?
In programming languages, if you hold double value in the int,it rounds the number to lower one thus if you do 15/10 it will return 1 as int and if you do 5/10 it will return 0. With this knowledge you can understand.
For example,let the number be 953,
while (temp != 0) {
temp = temp / 10;
factor = factor * 10;
}
1.Iteration temp = 95 , factor = 10
2.Iteration temp = 9 , factor = 100
3.Iteration temp = 0 , factor = 1000
end of while loop because temp is 0.
while (factor > 1) {
factor = factor / 10;
System.out.print((num / factor) + " ");
num = num % factor;
}
1.Iteration num = 953 factor = 100 , 953/100 = 9 (you get first digit)
2.Iteration num = 953%100 = 53 , factor = 10 , 53/10 = 5 (you get second digit)
3.Iteration num = 53%10 = 3 , factor = 1 , 3/1 = 3 (you get last digit)
End of while loop.
Actually it is basic math. When you want to extract nth digit of number, you just have to divide it by 10^n.
The modulus operator to extract the rightmost digit or digits from a number. For example, x % 10 yields the rightmost digit of x (in base 10). Similarly x % 100 yields the last two digits.
Here more info
If you would not care about flipping the order of digits, you could simply write
int num = sc.nextInt();
do {
System.out.println(num % 10);
num = num / 10;
} while(num != 0);
The modulo operation num % 10 calculates the remainder of dividing num by 10, effectively gets the digit at the lowest position ("ones"). 0 % 10 is 0 ... 9 % 10 is 9, 10 % 10 is 0 again, and so on. Then the division by 10 makes the old "tens" the new "ones", and the entire thing is repeated until 0 remains.
The hassle in your code is about emitting the digits in the "correct" order, highest position first, ones last. So it first checks how many digits are in your number, factor grows to the same size in the process. temp=temp/10; has the same role as num=num/10; in the short snippet (cutting a digit from the number in each iteration), and factor=factor*10 "adds" a digit to factor at the same time. [I just stop here as there is an accepted answer already explaining this]

optimization causes timeout? [duplicate]

This question already has answers here:
Number of consectuive sums error?
(2 answers)
Closed 5 years ago.
I am working on a program that takes an integer and finds the number of combinations of consecutive sums that the integer has:
The number 13 can be expressed as a sum of consecutive positive
integers 6 + 7. Fourteen can be expressed as 2 + 3 + 4 + 5, also a sum
of consecutive positive integers. Some numbers can be expressed as a
sum of consecutive positive integers in more than one way. For
example, 25 is 12 + 13 and is also 3 + 4 + 5 + 6 + 7.
I researched and read that it's the number of odd factors minus one. So I wrote a program that finds the number of odd factors and my answer is still wrong in certain cases. Any insight?
Code seems to work fine but there is a crash due to Timeout which is probably due to optimization error.
The constraints for possible input size is
1 to 10^(12)
static int consecutive(long num) {
while (num % 2 == 0) num /= 2; // 1st opt.
return consecutiveHelper(num)-1;
}
public static int consecutiveHelper(long num) {
long factorNumber = 1;
int count = 0;
while(factorNumber <= num / 2) { // 2nd opt.
if(num % factorNumber == 0) {
count++;
}
factorNumber += 2; // 3rd opt.
}
if (num % 2 != 0) {
count++;
}
return count;
}
Let's try to find a pseudo-optimized method to resolve your problem :
What you need to do is to decompose your number in prime factors.
For example, if you take 1200 :
1200 = 2*2*2*2*3*5*5 = 1 * 2^4 * 3^1 * 5^2
You can then analyze how you could get odd factors with those prime factors. A quick analyze will tell you that :
odd * odd = odd
odd * even = even
even * even = even
With that in mind, let's find all the factors we get with odd * odd :
1 * 1 = 1
3 * 1 = 3
5 * 1 = 5
5 * 3 = 15
5 * 5 = 25
5 * 5 * 3 = 75
A quick way to find these combinations without writing them all is the "plus 1 method" : add 1 to the number of occurences of each prime odd factor, and multiply them together :
We found that 1200 = 1 * 2^4 * 3^1 * 5^2, so we can do :
("number of 3" + 1) ("number of 5" + 1) = (1 + 1) ( 2 + 1) = 6
There are 6 odd factors for the number 1200, and as you stated, remove 1 from that number to get the number of combinations of consecutive sums that 1200 has :
6 - 1 = 5 <-- woohoo ! finally got the result !
Now, let's look at the code. What we want to have is a Map, the keys being the prime factors and the values being the number of their occurences :
/*
If number is odd,
find the number in the keys and add 1 to its value.
If the number is not in the keys, add it with value = 1.
*/
public static void addValue(Map<Integer, Integer> factors, int i) {
if(i % 2 != 0) {
int count = factors.containsKey(i) ? factors.get(i) : 0;
factors.put(i, ++count);
}
}
/*
Classic algorithm to find prime numbers
*/
public static Map<Integer, Integer> oddPrimeFactors(int number) {
int n = number;
Map<Integer, Integer> factors = new HashMap<>();
for (int i = 2; i <= n / i; i++) {
while (n % i == 0) {
addValue(factors, i);
n /= i;
}
}
if(n > 1) addValue(factors, n);
return factors;
}
With that, let's try to print what the map contains for number 1200 :
public static void main(String[] args) {
int n = 1200;
System.out.println(oddPrimeFactors(n));
}
$n : {3=1, 5=2}
Good ! Now let's finish the program with the method we developed before :
public static int combinations = 1;
public static void main(String[] args) {
int n = 1200;
oddPrimeFactors(n).forEach((key, value) -> combinations *= (value + 1));
combinations--;
System.out.println(combinations);
}
$combinations = 5
Finished ! feel free to ask if you did not understand something !
Note : I tried my program with the max value Integer can handle and it took less than one second for my program to proceed, which seems pretty fast to me. It could probably be faster though, it's up to you to find the most optimized version of this code !

Make java give the the highest sum of 3 numbers out of 4 given

When given 4 numbers, how do i find which 3 numbers out of the 4 will give the greatest sum.
So if given 3 2 5 5, i want java to sum 3 5 5 for a total of 13
I have been searching for about 20 minutes and all i find is how the find the highest number of the 4 numbers. I know i absolutely can just write 16 lines of code comparing the 16 different combinations but i was hoping someone could point me in a faster direction.
First find the smallest number.
So for 3 2 5 5 it would be 2. Make sure you store this.
Thus, the numbers to sum are 3, 5 and 5
To get the total sum you need to add all the numbers together so:
3 + 2 + 5 + 5 = 15
And then minus the smallest number from the sum. So 15-2 which equals 13
First find the greatest of the four numbers and keep it aside.
Then find the greatest of the remaining three numbers and keep it aside.
Then find the greatest of the remaining two numbers and keep it aside.
Then sum up the numbers kept aside and display the result.
public static void main(String args[]) {
int[] vals = new int[4];
vals[0] = 3;
vals[1] = 2;
vals[2] = 5;
vals[3] = 5;
int result = sum4(vals);
System.out.println("Sum of x+y = " + result);
}
private static int sum4(int[] nums)
{
int retVal = 0;
int lowest = Integer.MAX_VALUE;
for (int i=0; i<nums.length; i++)
{
if (nums[i] < lowest)
lowest = nums[i];
retVal += nums[i];
}
retVal -= lowest;
return retVal;
}

Could someone please explain how this while loop works?

I do not understand how the while loop dissects the information. Could someone please explain how it works?
private static int sumDigits(int number) {
int sum = 0; //Initialize sum
int rem; //Initialize remainder
while (number > 0) { //If number is greater than 0 true
rem = number % 10; //<-- ??
sum += rem; //<-- ??
number = number/10; //<-- ??
}
return sum;
}
The key to understanding this code is the use of two operators - the remainder operator % and the integer division operator /.
The % operator produces the remainder from dividing by its right-hand side. In case of % 10 this means "get the last decimal digit of the number"
The / division operator discards the remainder, producing an integer result. Dividing an integer by zero discards its last digit.
For example, if you start with n = 1234 and do
int d = n % 10;
int r = n / 10;
then d would be 4 and r would be 123.
At this point it should be clear how the loop proceeds to termination, and how it accumulates the sum of number's digits as it goes through the iterations.
Filled in the comments where you noted you had trouble
private static int sumDigits(int number) {
int sum = 0; //Initialize sum
int rem; //Initialize remainder
while (number > 0) { //If number is greater than 0 true
rem = number % 10; //rem now contains the remainder of the number / 10
//Keep in mind, number % 10 will give you the rightmost digit in your number
sum += rem; //add the remainder to your running total
number = number/10; //divide your number by 10 so you can find
//the next right most digit in your number
}
return sum;
This example tries to sum all the digits of a number % is used to get the last digit on each while loop and divided by 10 is done to reduce the number and sum is added for all digits see the inline comment by me
private static int sumDigits(int number) {
int sum = 0; //Initialize sum
int rem; //Initialize remainder
while (number > 0) { //If number is greater than 0 true
rem = number % 10; //remainder after division by 10 e.g 12%10=2
sum += rem; //sum=sum+rem //<-- ??
number = number/10;//reduce one number by dividing to 10 //<-- ??
}
return sum;
}
Let's step through the code with an example. Let's call sumDigits(1234).
The first time through the while loop, number equals 1234. rem = 1234 % 10, which evaluates to rem = 4 as the remainder from dividing 1234 by 10 is 4 (which is the rightmost digit in number). sum += rem evaluates to sum += 4, so the value of sum is 4. Since number is an int, storing the value of itself divided by 10 results in 123 being stored in number.
The second time through the while loop, number equals 123. rem = 123 % 10, which evaluates to rem = 3 as the remainder from dividing 123 by 10 is 3 (which is the rightmost digit in number). sum += rem evaluates to sum += 3, so the value of sum is 7, since sum was equal to 4 at the end of the last loop iteration. Since number is an int, storing the value of itself divided by 10 results in 12 being stored in number.
Repeat this two more times, and you'll end up with number equalling zero (as int(1/10) = 0), therefore, you'll exit the loop and sum will contain the sum of the digits in number.

Categories

Resources