Calculating the sum of number and its reverse in java - java

My question is based on a number manipulation in java. please, give any example for calculating the sum of any numbers and its reverse in java.for example, 123+321.

Public int sumReverse(int num){
int orignal=num;
int reverse=0;
While(orignal>0){
int remainder=orignal%10;
reverse=reverse*10+remainder;
orignal=orignal/10;
}
return num+reverse;
}

public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String n2s="";
int n1= sc.nextInt();
String n1s= String.valueOf(n1); //let n1s be the String of n1
for (int i=1;i<=n1s.length();i++){
n2s+=n1s.charAt(n1s.length()-i);
}
System.out.println(n2s);
int n2=Integer.valueOf(n2s);
int adit=n1+n2;
System.out.println(n1s+" + "+n2s +" = "+ adit);
}
In order to manipulate numbers they way you're looking for, it is easier to work that answer with the String of that number.
Scanner allow the user to type any number he/she wants to manipulate.
Hope this is usefull for you.

You could use StringBuilder also
int num = 123;
StringBuilder ob = new StringBuilder(Integer.toString(num));
ob.reverse();
System.out.println(num + Integer.valueOf(ob.toString()));
Store the data in StringBuilder and then add it to the original after reversing it.

Related

How to calculates the number by reversing its digits, and outputs a new number

I am trying to write a code that reads a three-digit number, calculates the new number by reversing its digits, and outputs a new number. I used Scanner. If there is a "0" at the beginning of the number then it should not appear
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int unity = (a%10)/100;
int tens = (a%100)/10;
int hundreds = a/100;
System.out.println(unity+""+tens+""+hundreds);
}
}
What's wrong with my code?
Try this code
Scanner scanner = new Scanner(System.in);
int a= scanner.nextInt();
String n=String.valueOf(a);
n=new StringBuilder(n).reverse().toString();
int end=Integer.parseInt(n);
System.out.println(end);
The problem with your code is that you are concatenating and printing the output as string.
You can add if statements:
if(unity == 0)
System.out.println(tens+""+hundreds);
Similarly an if statement for tens. By doing this you can skip zeros being printed.
You can also try this:
int result = (unity*100) + (tens*10) + hundreds;
System.out.println(result);
You can also go one more step ahead and write a recursive function to solve this.
Try this:
int unity = a%10;
int tens = parseInt(a%100/10);
int hundreds = parseInt(a/100);

Dynamic programming Very large data value

import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner s= new Scanner(System.in);
int t1=s.nextInt();
int t2= s.nextInt();
int n= s.nextInt();
double arr[]= new double[20];
for(int i=0;i<20;i++){
arr[i]=-1;
}
arr[1]= t1;
arr[2]=t2;
if(arr[n]!=-1){
System.out.println((long)arr[n]);
}
else{
for(int i=3;i<=n;i++){
arr[i]= arr[i-2] + Math.pow(arr[i-1],2);
}
System.out.println((long)arr[n]);
}
}
}
This code is a modified Fibonacci series. I want to calculate the tenth digit in this sequence. But the result is very big I want to ask in which type I should cast the answer ? I have used long but it failed...please suggest any other type ...
There's a special type for this kind of computation called BigInteger. Find more infos here.
Edit:
You can create a BigInteger from a String
BigInteger bigInt = new BigInteger("24");
or from an integer type
BigInteger fromInt = BigInteger.valueOf(24);

Output for finding kth digit from right of a^b does not come as Expected?

Given two numbers a and b, find kth digit from right of a^b?
Link for the problem:
http://www.practice.geeksforgeeks.org/problem-page.php?pid=302
MyApproach:
I took 4 numbers as Input.First was the number of test cases.Then,Input was numbers a b and k respectively(Seperated by space).I calculated a^b and then from right searched each number till the time kth digit is not equal to the count.If I get them equal I returned the remainder expected.
Below is the Code:
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
int count=1;
int a=sc.nextInt();
System.out.print(" ");
int b=sc.nextInt();
System.out.print(" ");
int k=sc.nextInt();
long result=(long) Math.pow(a,b);
if(k!=count)
{
while(k!=count)
{
count++;
int remainder=(int) (result%10);
result=result/10;
}
}
result=result%10;
System.out.println(result);
}
}
GeeksId Output:
Wrong !! Here your code Failed
Input:
7 6 3
And its Correct output is:
6
Eclipse ID:
Input:
7 6 3
Output
6
Wny I am getting Failed on geeksId?Is my solution do not produce correct output?
It seems like you did not follow the direction of the problem. The problem gives you a few constraints. you do not do a check for those. You should add the code to check that, so it will make sure you do not run into any exceptions.
I wanted to point out that you can just convert the Math.pow(a,b) result to string, and print the length - k char using the charAt function. This will make it very easy. and gets rid of the loops.
Code for that part is:
String tempString = String.valueOf(result);
System.out.println(tempString.charAt(tempString.length() - k));
Hope this puts you in the right direction.
Can also be done this way without much String operations and not expecting the intermediate output a^b to store in long data type,
private void handle() {
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
for(int i = 0; i < T; i++) {
findKthDigit(scanner);
}
scanner.close();
}
private void findKthDigit(Scanner scanner) {
int a = scanner.nextInt();
int b = scanner.nextInt();
int k = scanner.nextInt();
System.out.println((int)((Math.pow(a, b) % Math.pow(10, k))
/ Math.pow(10, k-1)));
}
As requested, your program is modified to make it work in GFG system,
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
int count=1;
int a=sc.nextInt();
//System.out.print(" ");
int b=sc.nextInt();
// System.out.print(" ");
int k=sc.nextInt();
long result=(long) Math.pow(a,b);
if(k!=count)
{
while(k!=count)
{
count++;
int remainder=(int) (result%10);
result=result/10;
}
}
result=result%10;
System.out.println(result);
}
}
Hope this helps to understand. (however, you need to check other related exceptions for a good programming practice)

Collections.reverse method not reversing entry

My code below is supposed to accept an integer from the user, and then print whatever integer they enter in reverse order. I am getting no errors, but when I run this program the integer is not being printed in reverse. Can someone please help me figure out why?
import java.util.*;
public class ReverseDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String response;
System.out.println("Please enter a whole number.");
response = sc.next();
reverseDigit(response);
}
public static void reverseDigit(String digit) {
ArrayList al = new ArrayList();
al.add(digit);
Collections.reverse(al);
System.out.println("Your number in reverse order is: " + al);
}
}
You misinterpreted what Collections.reverse does. This method reverses the list that you gave, not its content. Since you called this method with a list having a single element, the result will be the same list.
If you want to reverse a String, please refer to this question.
As a side-note: do not use raw types like ArrayList, this will get into trouble. Prefer the type-safe way ArrayList<String>.
Try this code.
ArrayList al = new ArrayList();
al.add(new StringBuffer(digit).reverse().toString());
If you have a collection of one, it is the same in reverse order as forward.
If you want to reverse the string representation of an integer, you can use StringBuilder to reverse the digits.
StringBuilder sb = new StringBuilder();
sb.append(digits);
sb.reverse();
System.out.println("Your number in reverse order is: "+ sb);
If you want to reverse a String why are you adding it to a list ?
Use this :
String s = sc.next();
StringBuilder sb = new StringBuilder(s);
System.out.println(sb.reverse());
The reverse(List<?>) method is used to reverse the order of the elements in the specified list. Since there is only one item in your collection, reverse order is same as the initial list. You can use the below code as you are trying to reverse an integer.
package com.stackoverflow.answer;
import java.util.*;
public class ReverseDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a whole number: ");
int number = scanner.nextInt();
System.out.println(String.format("Your number in reverse order is: %d", reverse(number)));
scanner.close();
}
public static int reverse(int x) {
return reverse(x, 0);
}
private static int reverse(int x, int y) {
return x == 0 ? y : reverse(x / 10, y * 10 + x % 10);
}
}

Converting decimal to binary in java having trouble with reversing order

Hey so I'm taking my first cs course ever at my university its taught in java. I'm having trouble converting decimal to binary. I seem to be able to get the correct output but its in reverse order, and I have no idea how to put it in the correct order, here is what I've coded so far,
import java.util.*;
public class lab6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number to convert to binary: ");
int x = input.nextInt();
int y;
String y1="";
while(x!=0){
y=x%2;
x=x/2;
y1 = Integer.toString(y);
System.out.print(y1+" ");
}
}
}
You can store the digits in some container(e.g. ArrayList) and then iterate it back to front printing each digit as you iterate.
It seems you are showing the output in correct order only. But if you want to reverse the current output you can use below code:
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number to convert to binary: ");
int x = input.nextInt();
int y;
String y1="";
String reverse = "";
while(x!=0){
y=x%2;
x=x/2;
y1 = Integer.toString(y);
// System.out.print(y1+" ");
reverse = y1+" "+reverse;
}
System.out.println("Reverse Order :"+reverse);
For adding to Ivaylo answer, you can also store it in a StringBuilder and reverse it using reverse method.

Categories

Resources