I need to implement a recursive method printDigits that takes an integer num as a parameter and prints its digits in reverse order, one digit per line.
This is what I have so far:
public class PrintDigits {
public static void main(String[] args) {
System.out.println("Reverse of no. is " + reversDigits(91));
}
/* Recursive function to reverse digits of num */
public static int reversDigits(int number) {
if (number == 0)
return number;
else {
return number % 10;
}
}
}
I feel like there is only one line of code that I am missing, but not sure what I need to do to fix it.
public static void main(String[] args) {
reverseDigits(98198187);
}
/* Recursive function to reverse digits of num */
public static void reverseDigits(long number) {
if (number < 10) {
System.out.println(number);
return;
}
else {
System.out.println(number % 10);
reverseDigits(number/10);
}
}
This doesn't exactly answer the question, but it actually computes the entire reversed number instead of printing the digits as they are calculated. The result is an int with the digits in reversed order. Much more powerful than printing out the string version of the numbers one by one:
public class Reverse {
public static void main(String[] args) {
// input int parameter
int param = Integer.parseInt(args[0]);
System.out.println(reverse(param));
}
public static int reverse(int input) {
return reverse(input, 0);
}
private static int reverse(int original, int reversed) {
// get the rightmost original digit and remove it
int rightmost = original % 10;
original -= rightmost;
original /= 10;
// add rightmost original digit to left of reversed
reversed += rightmost * Math.pow(10, numDigits(original));
return (original == 0)
? reversed
: reverse(original, reversed);
}
public static int numDigits(int number) {
number = Math.abs(number);
if (number >= 10) {
return 1 + numDigits(number /= 10);
} else if (number > 0) {
return 1;
} else {
return 0;
}
}
}
public static void reversDigits(long number) {
System.out.println(number % 10);
if (number >= 10) {
reversDigits(number / 10);
}
}
This is shortest/simplest version so far;)
public static int reversDigits(int num) {
if(num < 1) {
return 0;
}
int temp = num % 10;
num = (num - temp)/10;
System.out.println(temp);
return reversDigits(num);
}
This will print the digits one at a time in reverse order. You don't need to do System.out in your main method.
I found I had to pick off the highest digit (on the left) and work towards the rightmost digit. I couldn't get a recursive one to work going from right to left.
public static int reverseItRecursive(int number)
{
if (number == 0)
return 0;
int n = number;
int pow = 1;
while (n >= 10)
{
n = n / 10;
pow = pow * 10;
}
return (n + reverseItRecursive(number - n*pow)*10);
}
This should work
int rev = 0;
int reverse(int num)
{
if (num < 10) {
rev = rev*10 + num;
}
else {
rev = rev*10 + (num % 10);
num = reverse(num / 10);
}
return rev;
}
//Try out this, recursion with singe variable using Math class.
public static void main(String[] args) {
// Let the number be 139
int n=139;
System.out.println("reverse is "+rev(n));
}
static int rev(int n){
if (n==0)return 0;
else {
return n%10*(int) Math.pow(10,(double) (int)Math.log10(n))+rev(n/10);
}
}
This method reverse the integer and returns the result without using any string functions, Math, or by just printing
public class ReverseNumber {
public static void main (String[] args) {
ReverseNumber rNumber = new ReverseNumber();
System.out.println(rNumber.reverseRecursive(1234,0)); // pass zero to initialize the reverse number
}
public int reverseRecursive(int n, int reverse) {// n - the number to reverse
// System.out.println(n);
if (n != 0){
reverse = reverse * 10;
reverse = reverse + n %10;
n = n/10;
} else {
return reverse;
}
return reverseRecursive(n,reverse);
}}
public void reverse(int num){
System.out.print(num %10);
if(num / 10 == 0){
return;
}
reverse(num /10);
return;
}
This is very shortest/simplest way in two lines code:
public static int reverseNumber(int n)
{
System.out.println(n % 10);
return (n/10 > 0) ? reverseNumber(n/10) : n;
}
I came looking for a more elegant version than mine, but perhaps this just requires a bit of a messy algorithm. Mine also returns the actual integer value which I agree is much more useful than only printing the string:
Mine:
public static int reverse(int n){
if(n<10)return n;
return n%10*(int)Math.pow(10,(int)Math.log10((double)n)) + reverse(n/10);
}
so this returns the last digit, multiplied by 10^current power + (recursive call)
Here you go :
static String reverseDigits(int n)
{
String N = "";
if ( n== 0)
return N;
else
{
N += n%10;
return N + reverseDigits(n/= 10);
}
}
This is of course returned as String.
If you want it as int all you have to do is parse it using Integer.parseInt()
//Reverse a number using recursion by bibhu.rank
public class Rev_num {
public static int revnum(int x){
int temp1=x,temp2=1;
if(x<10){
return x;
}
while(temp1>=10){
temp2*=10;
temp1/=10;
}
if(((x%temp2) < (temp2/10))&& x%temp2!=0){
int c=temp2;
while(c> x%temp2){
c/=10;
}
c=temp2/c;
temp2=x%temp2;
return((temp1)+(c*revnum(temp2)));
}
temp2=x%temp2;
return (temp1+(10*revnum(temp2)));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter a number");
Scanner y=new Scanner(System.in);
System.out.println(revnum(y.nextInt()));
y.close();
}
}
public class reverseIntRec{
public static void main(String args[]) {
System.out.println(reverse(91));
}
public static int reverse(int x) {
String strX = String.valueOf(x);
if (Math.abs(x) < 10)
return x;
else
return x % 10 * ((int) Math.pow(10, strX.length()-1)) + reverse(x/10);
}
}
Here is my answer return as integer. I converted x into string to see how many 0s you should multiply with.
For example: reverse(91) returns 1 * 10 + reverse (9), and that returns 10 + 9 = 19.
Relatively simple since you need to print one digit per line. You also state that you print its digits, which implies that leading zeros are still going to be displayed. Our test case
123000 prints :
0
0
0
3
2
1
here is the code, no while, no string, and no math library :
private void printIntegerDigitsReversed(int i) {
if (i / 10== 0 ){
System.out.println(i);
}
else{
printIntegerDigitsReversed(i%10);
printIntegerDigitsReversed(i/10);
}
}
Related
How do I make a function return the sum of all digits until it becomes a 1 digit number, using recursion? I was able to make a function that gets the sum of all digits, but cant seem to find a way to recursively sum the digits of the sum itself:
class sum_of_digits
{
static int sum_of_digit(int n)
{
if (n == 0)
return 0;
return (n % 10 + sum_of_digit(n / 10));
}
public static void main(String args[])
{
int num = 12345;
int result = sum_of_digit(num);
System.out.println("Sum of digits in " +
num + " is " + result);
}
}
This code prints the sum of '12345', which is 15. But I need to change it so it prints the sum of 1 + 5, which is 6.
do you think it is possible to make it work without an additional
method?
Why can't we just let the recursion do the work for us and simply say:
static int sum_of_digit(int n)
{
if (n < 10)
return n;
return sum_of_digit(n % 10 + sum_of_digit(n / 10));
}
Things will become a lot easier if you define an additional recursive "layer" in conjunction with sum_of_digit. This new function can call sum_of_digit until it has a single digit as a result. Here is what I mean:
static int sum_to_one_digit(int n) {
if(n/10 == 0) return n;
return sum_to_one_digit(sum_of_digit(n));
}
The code from main will be:
public static void main(String args[])
{
int num = 12345;
int result = sum_to_one_digit(num);
System.out.println("Sum of digits in " +
num + " is " + result);
}
You could add a clause at the end to check whether the sum is smaller than 10, if it isn't then recursively call it again with the newly calculated sum, ie.
static int sum_of_digit(int n)
{
if (n == 0)
return 0;
int temp = (n % 10 + sum_of_digit(n / 10));
if (temp < 10)
return temp;
return sum_of_digit(temp);
}
There are several ways to do it, one would be like this if global variables are allowed :
public class Sum_of_digits{
static int sum = 0;
public static void main(String args[]){
int n = 12345;
System.out.println(sum_of_digit(n));
sum = 0;
}
static int sum_of_digit(int n){
if(n==0){
if(sum/10 == 0){
return sum;
}else{
n=sum;
sum=0;
}
}
sum = sum+(n%10);
n=n/10;
return sum_of_digit(n);
}
}
and if Global variable are not allowed then passing sum as a parameter will help :
public class Sum_of_digits{
public static void main(String args[]){
int n = 12345;
int sum = 0;
System.out.println(sum_of_digit(n,sum));
}
static int sum_of_digit(int n,int sum){
if(n==0){
if(sum/10 == 0){
return sum;
}else{
n=sum;
sum=0;
}
}
sum = sum+(n%10);
n=n/10;
return sum_of_digit(n,sum);
}
}
Here we are just shifting the focus from n to sum to evaluate the condition when the loop/recursion will terminate.
My Code doesn't print out Triangular Numbers according to the formula, but only loops the number 1.
What is my mistake?
public class Triangular{
public static void main(String[] args) {
int n = 1;
int t = (n * (n + 1)) / 2;
while(n <= 10) {
n++;
System.out.println(t);
}
}
}
Although you are increasing n by one, you are not recalculating the value of t inside the loop.
Try calculating the value of t inside the loop, for example:
public static void main(String[] args)
{
int n = 0;
int t = 0;
while (n <= 10)
{
n++;
t = (n * (n + 1))/2;
System.out.println(t);
}
}
Each time you increase the value of n, you need to recalculate the value of t by passing the new value of n into the formula.
t is not recalculated when n changes. You need to assign it inside the while loop. Also, you may as well just do this:
public class Triangular {
public static void main(String[] args) {
int n = 1;
int t = 1;
while(n <= 10) {
System.out.println(t);
n++;
t += n;
}
}
}
I'm trying to create a recursive function that returns the average of the digits in a number. For example the average of the number 123 is 2.
I know how to write a function that sums the digits.
public static int sum (int n) {
if (n<10)
return n;
return n%10 + sum(n/10);
}
I also know how to count the digits
public static int numCount(int n) {
if (n<10)
return 1;
return 1 + numCount(n/10);
}
However I can't figure out how to calculate the average without using pre existing functions.
You can recursively iterate the array while keeping both accumulative sum and an index that shows which items were already iterated:
public class MyClass {
public static void main(String args[]) {
int[] arr = {1,2,3};
System.out.println(avg(arr)); // 2.0
}
private static double avg(int[] arr) {
return avg(arr, 0, 0);
}
private static double avg(int[] arr, int index, int sum) {
if (index == arr.length) {
return (double) sum / index;
}
return avg(arr, index + 1, sum + arr[index]);
}
}
Demo
Try this:
int recursive(int num, int startingSize) {
if(num < 10){
return num;
}
num = num % 10 + recursive(num/10, startingSize++);
return num/startingSize;
}
and for example : recursive(123, 1)
count=0;
public static int sum (int n) {
count++;
if (n<10)
return n;
return n%10 + sum(n/10);
}
double average = (double)sum(123)/count;
System.out.println("average:"+ average);
I mean if we are just talking numbers we don't even need recursive functions here
String s = Double(10.45).toString();
Int size = s.length();
int count = 0;
Int sum = 0;
for (int i = 0; i < size; I++ ) {
try {
sum += Integer.valueOf(s[i]);
++count;
} catch (Exception e) {}
}
return sum / count;
That should give you an. Average regardless of number, whole or real.
I have to write a boolean method that checks if a number n is a circular prime, using only integer computations, so no Strings. I wrote two other methods that have to be included.
boolean isPrime(int n) {
if (n < 1) {
return false;
} else if (n == 1 || n == 2) {
return true;
} else if (n % 2 != 0) {
for (int i = 3; i < n; i+=2) {
if (n % i == 0) {
return false;
}
}
return true;
} else {
return false;
}
}
This checks if the number is a prime.
int largestPowerOfTen(int n) {
for (int i = 1; i < n * 10; i*=10) {
if (n / i == 0) {
return i / 10;
}
}
return 1;
}
This returns the largest power of ten of the number. For instance, 23 would return 10, 704 would return 100, etc.
I had the idea to put every digit into an array and move the digits around from there, but I'm stuck at the moving part.
boolean isCircularPrime(int n) {
ArrayList<Integer> k = new ArrayList<Integer>();
int i = 0;
while (n != 0) {
k.add(n % 10);
n /= 10;
i++;
}
//???
}
So how do I move the digits around?
Assuming a "circular prime number" is a number that is a prime number for all rotations of the digits...
You can't just rotate the number, because zeroes won't be conserved.
First break up the number into an array - each digit of the number an element of the array. Use n % 10 to find the last digit, then n /= 10 until n == 0.
Create a method the generates a number from the array with a specified starting index. This is the crux of the problem, and here's some code:
private static int generate(int[] digits, int index) {
int result = 0;
for (int i = 0; i < digits.length; i++) {
result = result * 10 + digits[(index + i) % digits.length];
}
return result;
}
Then loop over every possible starting index for your digits and check if it's prime.
The remaining code I leave to the reader...
import java.util.Scanner;
class CircularPrime
{
public boolean prime(int n)
{
int lim=n,count=0;
for(int i=1;i<=lim;i++)
{
if(n%i==0)count++;
}
if(count==2)
return true;
else
return false;
}
public int circlize(int n)
{
int len,x,y,circle;
len=(""+n).length();
x=n/(int)Math.pow(10,len-1);
y=n%(int)Math.pow(10,len-1);
circle=(y*10)+x;
return circle;
/**
Another way using String
String str = Integer.toString(n);
String arr = str.substring(1)+str.charAt(0);
int a = Integer.parseInt(arr);
return a;
**/
}
public void check(int n)
{
int a=n;
boolean flag=true;
System.out.println("OUTPUT:");
do
{
if(!(prime(a)))
{
flag=false;
break;
}
a=circlize(a);
System.out.println(a);
}while(a!=n);
if(flag)System.out.println(n+" IS A CIRCULAR PRIME");
else System.out.println(n+" IS NOT A CIRCULAR PRIME");
}
public static void main(String ar[])
{
CircularPrime obj = new CircularPrime();
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n=sc.nextInt();
obj.check(n);
}
}
I am trying to write a recursive function that when I call with number 5 for example then the function will calculate the sum of all digits of five.
1 + 2 + 3 + 4 + 5 = 15
The current code always returns 0, how can the amount each time the n?
public class t {
public static void main(String[] args) {
System.out.println(num(5));
}
public static int num(int n) {
int sum = 0;
sum += n;
if (n == 0)
return sum;
return num(n - 1);
}
}
thank you.
Instead of setting the sum to 0 you can -
Do this:
public int sumUp(int n){
if (n==1)
return 1;
else
return sumUp(n-1)+n;
}
The problem is you set the sum always 0.
public static void main(String[] args) {
System.out.println(num(5, 0));
}
public static int num(int n, int sum) {
if (n == 0) {
return sum;
}
sum += n;
return num(n - 1, sum);
}
public static int withRecursion(List<Integer> list) {
int size = list.size();
int a=0;
if(list.isEmpty() == true) {
return 0;
}else {
a = a + list.get(0) + withRecursion(list.subList(1, size));
return a;
}
}