Java recursive method which adds up digits of an argument [duplicate] - java

This question already has answers here:
How to write a recursive method to return the sum of digits in an int?
(13 answers)
Closed 7 years ago.
So I have to write recursive method that adds up value of digits within a certain number. For example, digitSum (1234) returns 10 (which is the sum 1+2+3+4).
So far I have this:
public static int digitSum (int n) {
if(n<10) { return n ;} //basecase
 else return !!! ;
}
What should I add in the !!! part, thank you

Just write it in plain english: when you have 1234, initial step should be to do sum(123) + 4
When you convert it to code:
public static int digitSum (int n) {
if(n<10) {
return n
}
else
return n%10 + digitSum(n/10);
}
n%10 gives you the last digit, n/10 gets you the remaining part.
When you have n=1234, n%10 = 4 and n/10 = 123. So according to your plain english sum(123) + 4 it should be digitSum(n/10) + (n%10)

Homework?
1234 remainder 10 is 4, 1234 / 10 is 123 you schould return digitSum(123) + 4

Related

How to find the sum of a number? [duplicate]

This question already has answers here:
How to sum digits of an integer in java?
(22 answers)
Closed 1 year ago.
Suppose
int n = 5
I want to find out the sum of n number. For example:- if n is given by user as 5 then in number array from 1 to 30 we have sum of n number is 14 and 23. Which is int number = 1+4= 5 and 2+3 = 5 that is number == n.
To reduce double digits i.e., if user put 15 then:-
reduce(int doubleDigit){
return (doubleDigit-1) %9 +1;
So to reduce 15 i.e., 1+5=6
But to calculate the sum of 6, how to find? What I want as a result is that when ans is 6 then the output should be 6, 15 (1+5=6) and 24 (2+4=6) which is sum of two digits is equal to ans in the range between 1 to 30.
So do I need to reverse the reduce function or is their any method to solve.
Small code hint will be very helpful.
There is a semi-tautological function for doing this:
public int sumDigits (int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
return sum;
}

Why do we get 1 as remainder on the second println? [duplicate]

This question already has answers here:
How Does Modulus Divison Work
(19 answers)
Closed 5 years ago.
package PracticePackage;
public class whileLoop {
public static void main(String[] args) {
int i=1;
System.out.println("Quotient "+i/2);
System.out.println("Remainder "+i%2);
}
}
this is the fomula that Java uses to yield the remainder of its operands:
(a/b)*b+(a%b)
where a is the dividend and b is the divisor.
so in your case it's like:
int i = 1;
int b = 2;
int result = (i / b) * b + (i % b);
hence the result 1 rather than 0
1/2 = 0.5
you defined i as int
Integral division in java takes floor of the answer if the answer is a real number so 1/2 becomes 0, making 1%2 equal to 1
I hope that explains.
because integers are not real numbers so you get 1 as answer and the real part of remainder is ignored since you defined i as an integer

How to implement a recursive binary search algorithm? [duplicate]

This question already has answers here:
Binary Search (recursive) [closed]
(3 answers)
Closed 6 years ago.
I need to implement a recursive binary search algorithm for an integer array sorted in ascending order (i.e 1,2,3,4...).
The array I have contains the following numbers:
0 0 0 0 0 0 0 1 2 2 3 3 3 3 5 6 7 7 7 9
However, my current implementation of binary search only finds the numbers to the right of 3. For some reason, it doesn't find 9, 7, 6, and 5.
below is my code:
private int srchHelper(int[] array, int first, int last, int x) {
if (first > last) return - 1;
int mid = (first + last) / 2;
if (array[mid] == x) {
return mid;
}
if (array[mid] < x) {
return srchHelper(array, (mid + 1), last, x);
}
else return srchHelper(array, (mid - 1), last, x);
}
Make sure you're clear about what the algorithm does, and then take a good long look at your recursive calls.

Summing a number's digits in Java [duplicate]

This question already has answers here:
Separating the Digits in an Integer - exercise from Deitel's Java book
(11 answers)
Closed 7 years ago.
Let's say you have an integer '75'. Normally, in your head, you can add the '7' with the '5' in order to get '12'. So you split the number '75' into two different numbers 7 and 5 then add them together. That leads to my question, how can you perform that in java? Is there a Math method that does it for you?
You can use plain maths
int i = 75;
int a = i / 10; // 7
int b = i % 10; // 5
int c = a + b; // 12
You can use some code like:
int num=75;
int sum_digits=0;
while(num>0){
int digit = num%10;
num /= 10;
sum_digits += digit;
}

what this method does - interview [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The following is an interview question... how can you start solve this kind of a question ? is there a general algorithm for such a questions ?
The question is to explain what this method does. I know what she gives for some inputs I tried (and it's OK), but I really don't know how to start solve this kind of a questions...
public boolean what (int num)
{
boolean ans = true;
for (int x = 2; (x*x <= num) && ans; x=x+1)
{
if ((num % x) == 0)
ans = false;
}
return ans;
}
thx !
let num = 10
public boolean what (int num)
{
boolean ans = true;
for (int x = 2; (x*x <= num) && ans; x=x+1)
{ //^ multiply x with x will give (4,9).. When x = 4, than (16<= num) = false
if ((num % x) == 0) // divide 10 by (2,3) if reminder is zero that means 10 is not prime
ans = false; // set ans to false so that for loop can be terminated or just break;
}
return ans;
}
Reverse engeering process you can follow, provide the some sample input and get the output by which you can determine the result.
Choose your input sensibly so that it would easy to solve the problem.
In present case -
Input : 1 return : true
Input : 2 return : true
Input : 3 return : true
Input : 4 return : false
Input : 5 return : true
...
Input : 9 return : false //aha...it seems to be prime number
...
Input : 111 return : false
So in this case its prime number logic.
You can find it running the method with several random inputs,
and try to find the relation between INPUT you gave and OUTPUT that appeared.
Before getting to conclusion just check it Known Output first and then declare your answer.
It checks if the num is a prime.
To find out what a method does read the code and try to understand what it is doing. You may also try some inputs. For good code the names of variables and methods also help a lot (which is not the case here).
However, if the method implements an algorithm you do not know and you do not know the context of the problem that is being solved you probably never find out what it does.
In the above program initially the number is assumed to be not prime. If any number greater than 2 and less than or equal to the square root of the number divide the given number then the number is not prime.
The method returns true if the number is not prime and returns false if the number is prime.
Purpose of method : to find out prime numbers.
This method gives an output of booleaan ans = 'true' , if input number is prime number.
Else it gives a return value of false.
It follows the simplest logic to find out if a number is prime or not..
for example if a number is 11 ,
Step 1 - we multiply it with a num till (num*num) is smaller than 11. {no need to test beyond value bigger then num*num, as all possible cases are tested }.
Step 2 - check if remainder of dividing 11/2 is zero or not , if remainder is not 0 then 11 is not prime.if it divides we go back to step 1
So the loop will be ..
Step 1 num = 11 , x = 2
Step 2 11%2 != 0 so goto step 1 , num undivisible
Step 1 num =11 , x = 3
Step2 11%3 != 0
Step 1 num = 11 , x = 4 but x*x = 16 and 16> 11 so no more looping and 11 is prime as it wasn't divisible with any number till x=3.
another example can be 38..
step 1 num 38 , x=2
step 2 38%2 ==0 , so remainder = zero and ans = false thus no more looping through and '38' is not prime.
a more advanced approach to finding a number if its prime or not could be to test its divisibility only against prime numbers. which is actually more efficient in case we have quite bigger numbers as input.
public boolean what (int num) // number to be tested is passed
{
boolean ans = true; // default value
for (int x = 2; (x*x <= num) && ans; x=x+1) //looping till num is found divisibl
{
if ((num % x) == 0)
ans = false; // ans is false in case num is not prime
}
return ans; // num is prime
}
Hope the explanation helps.. message me in case of any doubt or help.

Categories