I want to get an output that displays something like 1*2*3*4 but instead I get 4*3*2*1
this is my code:
public static int fact(int n)
{
if(n ==1)
return 1;
else
return n * fact(n-1);
}
public static int factorForm(int n)
{
System.out.print(n);
if (n == 1)
return 1;
else
{
System.out.print("*");
return n + '*' + factorForm(n-1);
}
}
You are calling fact(4)
Then you print
Then you call fact(3)
If you invert that you'll get what you want:
public class fact {
static int f(int n)
{
if (n ==1 )
{
System.out.print(1);
return 1;
}
int ret= (n * f(n-1));
System.out.print("*");
System.out.print(n);
return ret;
}
public static void main(String[] args)
{
int ret=f(4);
System.out.print("=");
System.out.println(ret);
}
}
To reverse the output, n should be printed after making the recursive call:
public static int factorForm(int n)
{
if (n == 1)
{
System.out.print(1);
return 1;
}
else
{
int rest = factorForm(n-1); // prints 1*2*...*n-1
System.out.print("*");
System.out.print(n);
return rest * n;
}
}
The expression n + '*' + factorForm(n-1) performs integer addition, not multiplication or string concatenation. I changed it to perform multiplication. If the intention is to return the string that was printed, the return type and the type of rest should be changed to String, the return value in the base case should be "1", and that expression should be changed to rest + "*" + n.
Return after printing as below, more importantly understand how recursion works:
public static int factorForm(int n)
{
if (n == 1){
System.out.print("1*");
return 1;
}
else
{
int val = n * factorForm(n-1);
System.out.print(n + "*");
return val;
}
}
if you want to get like 1*2*3*4 result. i think you can do this.
this is my code:
public static String fact(int n) {
if (n < 1) {
throw new RuntimeException("n must be int type and up 0");
}
else if (n == 1) {
return "1";
} else {
return n + "*" + fact(n - 1);
}
}
public static String factorForm(String str) {
String [] arr = str.split("\\*");
String [] newArr = new String[arr.length];
String result = "";
if (arr.length > 1) {
for (int i = 0; i < arr.length; i++) {
newArr[arr.length - i - 1] = arr[i];
}
for (int i = 0; i < newArr.length; i++) {
result += newArr[i] + (i != newArr.length - 1 ? "*" : "");
}
return result;
} else {
return str;
}
}
like this. you can get results what you get. may be complicated.
Related
I'm using recursion to solve the problem. On paper my answer should work so I went wrong with the code. However, I can't figure exactly where the problem is.
public class Partition {
public static void main(String[] args) {
System.out.println(part(6,4));
}
public static int part(int n, int m) {
if (n==0) {
return 1;
}
else if(m == 0 || n<0) {
return 0;
}
else {
return part(n-m, m) + part(n, m);
}
}
}
You need to reduce m only for the problem to return 9 as you indicated.
public static int part (int n, int m) {
if (n == 0) {
return 1;
} else if (m == 0 || n < 0) {
return 0;
} else {
return part(n - m, m--) + part(n, m);
}
}
I'm not sure what you're trying to do, but if it is to compute the combination it should look like this :
public static int part(int n, int m) {
if(m>n) { //This prevent a wrong input from the user
return part(m, n);
} else if (m==0 || m==n) { //This is your base case
return 1;
} else if(m < 0 || n<0) { //this should not happened, but you never know
return 0;
} else { //this is where you're making mistake(s)
//I don't know if I'm using the formula you are looking for
//But if not, make sure yours do not use part(n, m) otherwise it will run forever
return part(n-1, m) + part(n-1, m-1);
}
}
As I have already made the code just I have to add the required condition(1000 == 1 ! 0001). Can anybody help me out.
public class ReverseNum {
static void reverseInteger(int n) {
// Write your code here
if (n <= 0) {
System.out.print("-");
reverseInteger(n * -1);
} else if (n < 10) {
System.out.println(n);
}
else {
System.out.print(n % 10);
reverseInteger(n / 10);
}
}
public static void main (String args[]){
Scanner s = new Scanner(System.in);
int num = s.nextInt();
reverseInteger(num);
}
}
Be careful with negative numbers: they need special consideration (and also will break string reversal and parsing).
A solution that works with any int:
public static int reverse(int value) {
if (value < 0) {
// special handling for negative numbers
return 0 - reverse(-value);
}
int reversed = 0;
while (value > 0) {
reversed = reversed * 10 + (value % 10);
value /= 10;
}
return reversed;
}
Test cases:
assertEquals(0, reverse(0));
assertEquals(321, reverse(123));
assertEquals(98765, reverse(567890000));
assertEquals(-91, reverse(-19));
assertEquals(-2, reverse(-20000));
Try this code :
private static int reverseInteger(int n) {
if (n == 0) {
return n;
}
int symbol = n / Math.abs(n);
n = Math.abs(n);
String str = new StringBuilder(String.valueOf(n)).reverse().toString();
return symbol * Integer.parseInt(str);
}
Test cases:
#Test
public void test_reverseInteger() {
assertEquals(0, reverseInteger(0));
assertEquals(321, reverseInteger(123));
assertEquals(98765, reverseInteger(567890000));
assertEquals(-91, reverseInteger(-19));
assertEquals(-2, reverseInteger(-20000));
}
I have this method:
public static int parseInt(String str) {
if (isValidNumber(str)) {
int sum = 0;
int position = 1;
for (int i = str.length() - 1; i >= 0; i--) {
int number = str.charAt(i) - '0';
sum += number * position;
position = position * 10;
}
return sum;
}
return -1;
}
which converts a string into a integer. And as you can see it is (at the moment) in a if-statement with a method which checks if the input is a valid input for my purpose:
public static boolean isValidNumber(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(c >= '0' && c <= '9'){
return true;
}
}
return false;
}
I want the string to be number only (negative and positive) no other is allowed. At that time a string i.e 1a1a will be converted to a integer which it shouldn't whereas -1 will not be converted. I think you guys understand what I mean. I don't know how to do that.
Please help!
Try this:
CODE:
public class validNumbers {
public static void main(String[] args) {
System.out.println(parseInt("345"));
System.out.println(parseInt("-345"));
System.out.println(parseInt("a-345"));
System.out.println(parseInt("1a5b"));
}
public static int parseInt(String str) {
String numberWithoutSign = removeSign(str);
if (isValidNumber(numberWithoutSign)) {
int sum = 0;
int position = 1;
for (int i = numberWithoutSign.length() - 1; i >= 0; i--) {
int number = numberWithoutSign.charAt(i) - '0';
sum += number * position;
position = position * 10;
}
if(isNegative(str)){
return -(sum);
}else{
return sum;
}
}
return -1;
}
/**
* Removes sign in number if exists
*/
public static String removeSign(String number){
if(number.charAt(0) == '+' || number.charAt(0) == '-'){
return number.substring(1);
}else{
return number;
}
}
/**
* Determines if a number is valid
*/
public static boolean isValidNumber(String number) {
for (int i = 0; i < number.length(); i++) {
char c = number.charAt(i);
if(c >= '0' && c <= '9'){
continue;
}else{
return false;
}
}
return true;
}
/**
* Determines if a number is negative or not
*/
public static boolean isNegative(String number){
if(number.charAt(0) == '-'){
return true;
}else{
return false;
}
}
}
OUTPUT:
345
-345
-1
-1
To check if a string is a real number you can use a method like this:
public static boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {}
return false;
}
The problem is with your function isValidNumber. It should return a false on first occurrence of a non numeric value, as follows:
public static boolean isValidNumber(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(!(c >= '0' && c <= '9')){
if (i > 0) {
return false;
}
//This will only be invoked when `i == 0` (or less, which is impossible in this for loop), so I don't need to explicitly specify it here, as I have checked for `i > 0` in the above code...
if (c != '-' && c != '+') {
return false;
}
}
}
return true;
}
So i have to make a method that will return a value based on m or M in a string. so far i have this
public static int mIndex(String x) {
if (x.indexOf('M') >= 0) {
return x.indexOf('M');
}
if (x.indexOf('m') >= 0) {
return x.indexOf('m');
} else {
return -1;
}
}
The problem is that it only returns M if it is first in the String. Is there anyway for it to detect m or M, and then give a value based on that?
For something like that, a regular expression is your friend:
public static int mIndex(String x) {
Matcher m = Pattern.compile("[mM]").matcher(x);
if (m.find())
return m.start();
return -1;
}
Test
System.out.println(mIndex("kamdkMMM"));
System.out.println(mIndex("KAMDKmmm"));
System.out.println(mIndex("Hello World"));
Output
2
2
-1
Try this:
String s = "MarshmallowmmMaM";
System.out.println("Index of 'M':");
int index = s.indexOf("M");
while (index >= 0) {
System.out.println(index);
index = s.indexOf("M", index + 1);
}
System.out.println("Index of 'm':");
index = s.indexOf("m");
while (index >= 0) {
System.out.println(index);
index = s.indexOf("m", index + 1);
}
Output:
Index of 'M':
0
13
15
Index of 'm':
5
11
12
If you want to detect the first position of each case for letter M. "upper&lower".
public class Main {
public static int M_POSITION = -1;
public static int m_POSITION = -1;
public static void mIndex(String x) {
int i = 0;
while (i < x.length()) {
if (x.charAt(i) == 'M') {
if (M_POSITION == -1)
M_POSITION = i;
} else if (x.charAt(i) == 'm') {
if (m_POSITION == -1)
m_POSITION = i;
}
++i;
}
}
public static void main(String[] args) {
mIndex("adsm");
System.out.println(m_POSITION);
System.out.println(M_POSITION);
}
}
Problem:
Develop a recursive algorithm to determine if there is a palindrome hidden within a longer word or phrase. A palindrome is a word or phrase that has the same sequence of letters when read from left to right and when read from right to left, ignoring the spaces (e.g., Some like cake, but I prefer pie contains the palindrome I prefer pi).
Below is my code:
public class e125 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int i = 0;
String sLine = "Some like cake, but I prefer pie";
sLine.replaceAll("\\s+", "");
System.out.println(PlainRet(sLine, i));
}
public static String PlainRet(String sLine, int i) {
int nNum;
char c = 0;
String sPlain = "";
if (i >= sLine.length()) {
return "No Plaindrome";
}
c = sLine.charAt(i);
nNum = Isgood(sLine, c, i);
if (nNum != 0) {
for (; i < nNum; i++) {
sPlain += sLine.charAt(i);
}
return sPlain;
}
return PlainRet(sLine, i + 1);
}
public static int Isgood(String sLine, char c, int i) {
for (int j = i + 1; j < sLine.length(); j++) {
if (Character.toUpperCase(sLine.charAt(j)) == Character.toUpperCase(c)) {
if (Isplain(sLine, i, j)) {
return j;
}
}
}
return 0;
}
public static boolean Isplain(String sLine, int i, int j) {
if (Character.toUpperCase(sLine.charAt(j)) != Character.toUpperCase(sLine.charAt(i))) {
return false;
}
else if (i == j || j == i + 1) {
return true;
}
return (Isplain(sLine, i + 1, j - 1));
}
}
I keep getting an output of "I"
I have no idea what is wrong.
Like FatalError commented sLine.replaceAll() returns a new String. You need to reassign sLine or pass the results of the replaceAll() into the method.
You'll find a new error to fix after you do that, but it's just an off-by-one!