Write a recursive method digitSum that takes a non-negative integer in return fo
ID: 3808455 • Letter: W
Question
Write a recursive method digitSum that takes a non-negative integer in return for some of its digits. For example, digitSum(1234) returns 1 + 2 + 3 + 4 = 10. Your method should take advantage of the fact that it is easy to break a number into two smaller pieces by dividing by10 (ie, 1234/10 = 123 and 1234%10 = 4). For these methods, we do not need to construct any objects. Therefore, you can declare them to be static methods and call them directly from main: public static int digitSum(int n) {ellipsis} Subset Sum is an important and classic problem in computer theory. Given a set of integers and a target number, your goal is to find a subset of those numbers that sum to the target number, For example, given the set {3, 7, 1, 8, -3} and the target sum 4, the subset {3, 1} sums to 4. On the other hand, if the target sum were 2, the result is false since there is no subset that sums to 2.This problem is called the Knapsack Problem. Write a recursive method to rotate a string by N characters to the left. For example, rotateleft("ICS201", 2) should return "S201|C" This method can also be called statically since it does not need an object to solve the problem. An example of the method declaration would be: public static String rotatLeft(String stringToReverse, IntnumOfSpaces)Explanation / Answer
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Surya
*/
public class srtingOperation {
public static int digitSum(int n)
{
if(n==0)
return 0;
return digitSum(n/10)+(n%10);//calculating sum and returning
}
public static String rotateLeft(String s,int number)
{
int i=number;
if(i>s.length())
{
i = i%s.length();
}
int j = i;
String r="";
while(i<s.length())
{
r=r+s.charAt(i);//rotating
i++;
}
i=0;
while(i<j)
{
r=r+s.charAt(i);//rotating
i++;
}
return r;
}
public static void main(String argv[])
{
System.out.println("Sum of digits : "+digitSum(123));
System.out.println("String rotate to left: "+rotateLeft("hello",2));
}
}
output:-
run:
Sum of digits : 6
String rotate to left: llohe
BUILD SUCCESSFUL (total time: 0 seconds)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.