Making a number in reverse using for loop java - java

So I'm trying to reverse a number in java using a forloop, I get the right value but I'm not sure if thats the best way of doing it.
package forloops;
/*
% prints the last number in the sequence
/ prints every number except for the last one
*/
public class modulusForLoops {
public static void main(String[]args) {
int orig = 123456789;
int num = orig;
for (int i = 0; i < 1; i++) {
num = orig % 10; //9
int secondDigit = orig / 10; //12345678
int secondDigitPrinted = secondDigit % 10; //8
int thirdDigit = secondDigit / 10; //1234567
int thirdDigitPrinted = thirdDigit % 10; //7
int fourthDigit = thirdDigit / 10; //123456
int fourthDigitPrinted = fourthDigit % 10; //6
int fifthDigit = fourthDigit / 10; //12345
int fifthDigitPrinted = fifthDigit % 10;
int sixthDigit = fifthDigit / 10; //1234
int sixthDigitPrinted = sixthDigit % 10; //4
int seventhDigit = sixthDigit / 10; //123
int seventhDigitPrinted = seventhDigit % 10; //3
int eigthDigit = seventhDigit / 10; //12
int eigthDigitPrinted = eigthDigit % 10; //2
int lastDigit = eigthDigit / 10; //1
System.out.println(orig + " reversed is " + num + secondDigitPrinted + thirdDigitPrinted + fourthDigitPrinted + fifthDigitPrinted + sixthDigitPrinted + seventhDigitPrinted + eigthDigitPrinted + lastDigit);
}
}
}

You could simply convert it to String and using java.lang.StringBuilder reverse the string.
int orig = 123456789;
String numString = Integer.toString(orig);
String reversed = "";
for (int i = numString.length() - 1; i >= 0; i--) { // loop through the string from back to front
reversed += numString.charAt(i); // add each character to the resulting string
}
System.out.println(reversed);
Or alternatively
int orig = 123456789;
String numString = Integer.toString(orig); // convert int to String
String reversed = new StringBuilder(numString).reverse().toString(); // reverse string
System.out.println(reversed);

Let's stick with the logic you have in mind to reverse any number. For better understanding, let's list out the algorithm steps that you are using.
Repeat below steps until there are no digits left in the given number:
I) get the last digit from the number, i.e. lastDigit = number % 10
II) remove the last digit from the number, i.e. numberWithoutLast = number / 10
When we want to go through a sequence of steps multiple times, i.e. repeat them, we make use of the looping structures like for, while or do...while
Therefore, if we were to rewrite your program-the loop part-it would be as follows:
public static void main(String[] ar) {
int orig = 123456789;
int lastDigit = 0;
/* we'll use the copy of original number for step I & II
* instead of messing with the original number
*/
int numberWithoutLast = orig;
String reversed = ""; // we'll use this to store every last digit
for(int i = 0;
i < Integer.toString(orig).length(); /* this will repeat the loop for number of digits in "orig" */
i++) {
lastDigit = numberWithoutLast % 10;
reversed += Integer.toString(lastDigit);
numberWithoutLast = numberWithoutLast / 10;
}
// lastly we print the reversed number
System.out.println("Reversed Number: " + reversed);
}
This was the manual way of reversing an integer. For an automatic way, you can have a look at #Andreas's answer.

Just in case you want to know how to do it by modulus and loop. The idea is to pop the unit digit from the source and push it to the destination in every iteration, in a number way.
int orig = 123456789; //assume > 0
int num = 0;
for(int temp = orig;temp > 0;temp/=10)
{
num = num * 10 + temp % 10;
}
System.out.println(orig + " reversed is " + num);

Related

How to convert int number to two numbers witch first is made by odd bits and 2nd by even bits

How can I convert int=43707 to two other numbers?
The first number is made by value of odd bits. Second number is made by value of even bits.
int x = 43707; // 1010101010111011
var even = 0;
var odd = 0;
for (int i = 0; i<=31; i++) {
if(i%2 == 0) {
?
} else {
?
}
}
Your looking for the bitwise AND operation: &. you can use it together with a binary mask (normally specified in hex notation 0x00FF). so you need to do something like:
int x= 707; //10110011
int oddBits = 0x5555; //01010101
int evenBits = 0xAAAA; //10101010
int oddResult = x & oddBits;
System.out.println(oddResult);
int evenResult = x & evenBits;
System.out.println(evenResult);
which returns: 65 //00010001
and 642 // 10100010
Just convert int into digits as shown below:
List<Integer> digits = new ArrayList<Integer>();
while(x > 0) {
digits.add(x % 10);
x /= 10;
}
System.out.println(digits);
Once you have the separated the digits then apply the even odd logic. Here is complete code:
int x = 43707; // 1010101010111011
List<Integer> digits = new ArrayList<>();
while(x > 0) {
digits.add(x % 10);
x /= 10;
}
int i = 0;
int length = digits.size();
while (i < length) {
if(digits.get(i)%2 == 0){
System.out.println("Even Number" + digits.get(i));
} else {
System.out.println("Odd Number" + digits.get(i));
}
i++;
}
If you are looking for the Binary conversion then you can use the below code.
int x = 43707; // 1010101010111011
int testNumber;
String binaryNumber = Integer.toBinaryString(x);
for (int i = 0 ; i != binaryNumber.length() ; i++) {
char c = binaryNumber.charAt(i);
testNumber = Character.getNumericValue(binaryNumber.charAt(i));
if(testNumber == 0){
System.out.println("Even Number");
} else {
System.out.println("Odd Number");
}
System.out.println(c);
}
System.out.println(binaryNumber);
It converts the Int to Binary and then check even and odd numbers.
Hope, it works for you as per your desired output.
I came up to this:
int x = 43707;
String binary = Integer.toBinaryString(x);
System.out.println("binary=" + binary);
String odds = "";
String evens = "";
for (int i = binary.length() - 1; i >= 0; i--) {
if ((i + 1) % 2 == 0) {
odds += binary.charAt(i);
} else {
evens += binary.charAt(i);
}
}
System.out.println("odds=" + odds);
System.out.println("evens=" + evens);
int odd = Integer.parseInt(odds, 2);
int even = Integer.parseInt(evens, 2);
System.out.println("number from odd bits=" + odd);
System.out.println("number from even bits=" + even);
prints
binary=1010101010111011
odds=10100000
evens=11111111
number from odd bits=160
number from even bits=255
I'm counting right to left the bits.

get second digit from int

I have an int that ranges from 0-99. I need to get two separate ints, each containing one of the digits. I can't figure out how to get the second digit. (from 64 how to get the 6) This is my code:
public int getNumber(int pos, boolean index){//if index = 1 - first digit, if index = 0 - second digit
int n;
if(index){
n = pos%10;
}else{
if(pos<10){
n=0;
}else{
//????
}
}
return n;
}
You can do integer division by 10. For example, in the following code res should equal 4:
int res = 42 / 10;
Simply divide by 10.
...
if(index) {
n = pos/10;
}
...
Simple: in order to get any leading digit; just create a loop; and during each run, divide by 10.
In your case, you can even omit the loop ;-)
you can do:
if(index){
return x % 10;
}
return x / 10;
or maybe a little something
public int getNumber(....){
return index ? x % 10 : x / 10;
}
Just divide the number by 10. If it's int, the result will be int.
class Main {
public static void main(String[] args) {
int a = 8;
int b = 28;
int c = 99;
System.out.println(a / 10);
System.out.println(b / 10);
System.out.println(c / 10);
}
}
Here is a trick. Replace your //???? with below code.
Integer posInt= new Integer(pos);
n=Integer.parseInt( posInt.toString().substring(0, 1));
Complete code should look like,
public int getNumber(int pos, boolean index){//if index = 1 - first digit, if index = 0 - second digit
int n;
if(index){
n = pos%10;
}else{
if(pos<10){
n=0;
}else{
Integer posInt= new Integer(pos);
n=Integer.parseInt( posInt.toString().substring(0, 1));
}
}
return n;
}
Scanner scan = new Scanner(System.in);
System.out.println("Give a number");
int n = scan.nextInt();
int secondNumber = 0;
while (n > 9) {
secondNumber= n % 10;
n /= 10;
}
to find the first number you need to add to while a constant = n/10; (firstNumber = n / 10;)

Display numbers in characters as integers

int value = 1234;
char[] chars = String.valueOf(value).toCharArray();
How would I display those value as integers?
Almost there. You are missing an important piece though. You need to call sort() on Arrays
public static void main(String[] args) {
int value = 1234;
char[] arr = String.valueOf(value).toCharArray();
Arrays.sort(arr);
System.out.println(arr[0] + " " + arr[arr.length - 1]);
}
O/P :
1 4 // arr[0] is min and arr[arr.length-1] is max
You can do this using for loop ,only if you want to display these numbers seperately.I suggest you want to display all four digits in seperate four lines.it will be done by bellow code.
int value = 1234;
char [] chars = String.valueOf(value).toCharArray();
for(int i=0; i < chars.length ; i++ )
System.out.println(chars[i]);
public static void main(String[] args) {
int value = 1234;
List<Integer> output = new ArrayList<Integer>();
while (value > 0) {
output.add(value % 10);
value /= 10;
}
Collections.sort(output);
System.out.println("Min:" + output.get(0));
System.out.println("Max:" + output.get(output.size() - 1));
}
You will need a loop to pull of each individual digit and compare it to the current min/max :
int n = 36348;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
if (n > 0) {
while (n > 0) {
int digit = n % 10;
max = Math.max(max, digit);
min = Math.min(min, digit);
n /= 10;
}
}
System.out.println(min);
System.out.println(max);

Adding numbers which are stored in string variables

Given two non-negative numbers num1 and num2 represented as strings, return the sum of num1 and num2.
The length of both num1 and num2 is less than 5100.
Both num1 and num2 contain only digits 0-9.
Both num1 and num2 do not contain any leading zeros.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
I tried my solution but it doesn't work. Suggestions?
public class Solution {
public String addStrings(String num1, String num2) {
double multiplier = Math.pow(10, num1.length() - 1);
int sum = 0;
for (int i = 0; i < num1.length(); i++){
sum += ((((int) num1.charAt(i)) - 48) * multiplier);
multiplier /= 10;
}
multiplier = Math.pow(10, num2.length() - 1);
for (int i = 0; i < num2.length(); i++){
sum += ((((int) num2.charAt(i)) - 48) * multiplier);
multiplier /= 10;
}
return "" + sum;
}
}
You must not use any built-in BigInteger library or convert the inputs to integer directly.
Note that you are adding two integers of up to 5100 digits each. That is not that max value, but the max number of digits.
An int (your sum variable) cannot hold values like that. BigInteger can, but you're not allowed to use it.
So, add the numbers like you would on paper: Add last digits, write lower digit of the sum as last digit of result, and carry-over a one if needed. Repeat for second-last digit, third-last digit, etc. until done.
Since the sum will be at least the number of digits of the longest input value, and may be one longer, you should allocate a char[] of length of longest input plus one. When done, construct final string using String(char[] value, int offset, int count), with an offset of 0 or 1 as needed.
The purpose of this question is to add the numbers in the string form. You should not try to convert the strings to integers. The description says the length of the numbers could be up to 5100 digits. So the numbers are simply too big to be stored in integers and doubles. For instance In the following line:
double multiplier = Math.pow(10, num1.length() - 1);
You are trying to store 10^5100 in a double. In IEEE 754 binary floating point standard a double can a store number from ±4.94065645841246544e-324 to ±1.79769313486231570e+308. So your number won't fit. It will instead turn into Infinity. Even if it fits in double it won't be exact and you will encounter some errors in your follow up calculations.
Because the question specifies not to use BigInteger or similar libraries you should try and implement string addition yourself.
This is pretty straightforward just implement the exact algorithm you follow when you add two numbers on paper.
Here is working example of adding two strings without using BigInteger using char array as intermediate container. The point why double can't be used has been explained on #Tempux answer. Here the logic is similar to how adding two numbers on paper works.
public String addStrings(String num1, String num2) {
int carry = 0;
int m = num1.length(), n = num2.length();
int len = m < n ? n : m;
char[] res = new char[len + 1]; // length is maxLen + 1 incase of carry in adding most significant digits
for(int i = 0; i <= len ; i++) {
int a = i < m ? (num1.charAt(m - i - 1) - '0') : 0;
int b = i < n ? (num2.charAt(n - i - 1) - '0') : 0;
res[len - i] = (char)((a + b + carry) % 10 + '0');
carry = (a + b + carry) / 10;
}
return res[0] == '0' ? new String(res, 1, len) : new String(res, 0, len + 1);
}
This snippet is relatively small and precise because here I didn't play with immutable String which is complicated/messy and yield larger code. Also one intuition is - there is no way of getting larger output than max(num1_length, num2_length) + 1 which makes the implementation simple.
You have to addition as you do on paper
you can't use BigInteger and the String Length is 5100, so you can not use int or long for addition.
You have to use simple addition as we do on paper.
class AddString
{
public static void main (String[] args) throws java.lang.Exception
{
String s1 = "98799932345";
String s2 = "99998783456";
//long n1 = Long.parseLong(s1);
//long n2 = Long.parseLong(s2);
System.out.println(addStrings(s1,s2));
//System.out.println(n1+n2);
}
public static String addStrings(String num1, String num2) {
StringBuilder ans = new StringBuilder("");
int n = num1.length();
int m = num2.length();
int carry = 0,sum;
int i, j;
for(i = n-1,j=m-1; i>=0&&j>=0;i--,j--){
int a = Integer.parseInt(""+num1.charAt(i));
int b = Integer.parseInt(""+num2.charAt(j));
//System.out.println(a+" "+b);
sum = carry + a + b;
ans.append(""+(sum%10));
carry = sum/10;
}
if(i>=0){
for(;i>=0;i--){
int a = Integer.parseInt(""+num1.charAt(i));
sum = carry + a;
ans.append(""+(sum%10));
carry = sum/10;
}
}
if(j>=0){
for(;j>=0;j--){
int a = Integer.parseInt(""+num2.charAt(j));
sum = carry + a;
ans.append(""+(sum%10));
carry = sum/10;
}
}
if(carry!=0)ans.append(""+carry);
return ans.reverse().toString();
}
}
You can run the above code and see it works in all cases, this could be written in more compact way, but that would have been difficult to understand for you.
Hope it helps!
you can use this one that is independent of Integer or BigInteger methods
public String addStrings(String num1, String num2) {
int l1 = num1.length();
int l2 = num2.length();
if(l1==0){
return num2;
}
if(l2==0){
return num1;
}
StringBuffer sb = new StringBuffer();
int minLen = Math.min(l1, l2);
int carry = 0;
for(int i=0;i<minLen;i++){
int ind = l1-i-1;
int c1 = num1.charAt(ind)-48;
ind = l2-i-1;
int c2 = num2.charAt(ind)-48;
int add = c1+c2+carry;
carry = add/10;
add = add%10;
sb.append(add);
}
String longer = null;
if(l1<l2){
longer = num2;
}
else if(l1>l2){
longer = num1;
}
if(longer!=null){
int l = longer.length();
for(int i=minLen;i<l;i++){
int c1 = longer.charAt(l-i-1)-48;
int add = c1+carry;
carry = add/10;
add = add%10;
sb.append(add);
}
}
return sb.reverse().toString();
}
The method takes two string inputs representing non-negative integers and returns the sum of the integers as a string. The algorithm works by iterating through the digits of the input strings from right to left, adding each digit and any carryover from the previous addition, and appending the resulting sum to a StringBuilder. Once both input strings have been fully processed, any remaining carryover is appended to the output string. Finally, the string is reversed to produce the correct output order.
Hope this will solve the issue.!
public string AddStrings(string num1, string num2)
{
int i = num1.Length - 1, j = num2.Length - 1, carry = 0;
StringBuilder sb = new StringBuilder();
while (i >= 0 || j >= 0 || carry != 0) {
int x = i >= 0 ? num1[i--] - '0' : 0;
int y = j >= 0 ? num2[j--] - '0' : 0;
int sum = x + y + carry;
sb.Append(sum % 10);
carry = sum / 10;
}
char[] chars = sb.ToString().ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
Previous solutions have excess code. This is all you need.
class ShortStringSolution {
static String add(String num1Str, String num2Str) {
return Long.toString(convert(num1Str) + convert(num2Str));
}
static long convert(String numStr) {
long num = 0;
for(int i = 0; i < numStr.length(); i++) {
num = num * 10 + (numStr.charAt(i) - '0');
}
return num;
}
}
class LongStringSolution {
static String add(String numStr1, String numStr2) {
StringBuilder result = new StringBuilder();
int i = numStr1.length() - 1, j = numStr2.length() - 1, carry = 0;
while(i >= 0 || j >= 0) {
if(i >= 0) {
carry += numStr1.charAt(i--) - '0';
}
if(j >= 0) {
carry += numStr2.charAt(j--) - '0';
}
if(carry > 9) {
result.append(carry - 10);
carry = 1;
} else {
result.append(carry);
carry = 0;
}
}
if(carry > 0) {
result.append(carry);
}
return result.reverse().toString();
}
}
public class Solution {
static String add(String numStr1, String numStr2) {
if(numStr1.length() < 19 && numStr2.length() < 19) {
return ShortStringSolution.add(numStr1, numStr2);
}
return LongStringSolution.add(numStr1, numStr2);
}
}
For the sake of comprehension of the question
your method's name is addition
you are trying to do a power operation but the result is stored in a variable named multiplication...
there is more than one reason why that code doesnt work...
You need to do something like
Integer.parseInt(string)
in order to parse strings to integers
here the oficial doc

algorithm for adding the diagonals on a square or rectangular matrix, starting rightwise

I want to add the diagonals in a square or rectangular matrix to emulate the process of adding the partial results in a multiplying algorithm.
Like this:
2412
x 3231
---------
2412
7236
4824
+ 7236
---------
7793172
I need to run this, step by step, to satisfy the requirements of an online judge program. I have already figured out how to get the partial results of the multiplications (the humbers 2412, 7236, 4824, 7236) and I have placed them on a square matrix.
I realized I can get the addition result of this matrix by considering square or rectangular like:
2 4 1 2
7 2 3 6
4 8 2 4
7 2 3 6
and get the result of the addition by adding each diagonal (starting with the upper right one) and taking into account the carry of the addition and using an auxiliary array that has the same number of digits as number_of_digits_in_operand_a + number_of_digits_in_operand_b (operand a being 2412 and operand b being 3231, in this case).
For example, the array result, on its rightmost position should be:
result[(digits_a+digits_b)-1] = partialResult[0][3];
next:
result[digits_a+digits_b]=(partialResult[0][2] + partialResult[1][3] + carry) %10;
newCarry = (partialResult[0][2] + partialResult[1][3] + carry) / 10;
Well, I'm stuck writing the double nested loop that's supposed to add these diagonals starting with the upper right one. Help. Please.
I ended up using this (don't ask why it converts a BigInteger to an ArrayList and viceversa, it's a bizarre homework requirement).
public static BigInteger simpleMultiply(BigInteger x, BigInteger y) throws IOException {
char [] longerNum;
char [] shorterNum;
ArrayList<Integer> multResult= new ArrayList<Integer>(2000);
if(x.compareTo(y)>=0){ // x is a longer/equal num
longerNum = x.toString().toCharArray();
shorterNum = y.toString().toCharArray();
}
else { //y is a longer num
longerNum = y.toString().toCharArray();
shorterNum = x.toString().toCharArray();
}
//shorter num equals the number of rows in partial result
// longer num + 1 equals the number of columns in partial result
int [][] partialResult = new int [shorterNum.length][longerNum.length+1];
int pastCarry=0;
int result=0;
int carry=0;
for (int sIndex=(shorterNum.length-1); sIndex>=0; sIndex--){
pastCarry=0;
for (int lIndex = (longerNum.length-1); lIndex>=0; lIndex--)
{
int sInt = Integer.parseInt(""+shorterNum[sIndex]+"");
int lInt = Integer.parseInt(""+longerNum[lIndex]+"");
int product = sInt*lInt;
if (lIndex==0){
result = (pastCarry+product)% 10;
carry = (pastCarry+product) / 10;
pastCarry = carry;
partialResult [sIndex][lIndex+1] = result; //one more column element in partialResult
partialResult[sIndex][lIndex] = carry;
}
else {
result = (pastCarry+product) % 10;
carry = (pastCarry+product) / 10;
pastCarry = carry;
partialResult [sIndex][lIndex+1] = result;//one more column element in partialResult
}
}
}
for (int i=0; i<partialResult.length;i++)
for (int j=0; j<partialResult[0].length;j++)
{
System.out.print(partialResult[i][j] + " ");
if (j==partialResult[0].length-1){System.out.println();}
}
int auxColumn=0;
int diagonalAcum=0;
//add diagonals
int copyDigit=0;
int carryDigit=0;
int lastCarry=0;
rowCycle:
for (int column=partialResult[0].length-1; column>=0; column--){
diagonalAcum=0; //carryDigit=0;
diagonalAcum+=carryDigit;
auxColumn=column;
for (int row=0; row<partialResult.length; row++){
if (auxColumn+1 ==partialResult[0].length){
diagonalAcum+=partialResult[row][auxColumn++];
copyDigit=diagonalAcum % 10;
carryDigit=diagonalAcum / 10;
multResult.add(copyDigit);
continue rowCycle;
}
diagonalAcum+=partialResult[row][auxColumn++];
} //end row cycle
copyDigit= diagonalAcum % 10;
carryDigit=diagonalAcum / 10;
multResult.add(copyDigit);
if(column==0){
lastCarry = carryDigit;
}
}
carryDigit=0; //reset
int diagonal2Acum=0;
// diagonal2Acum +=lastCarry;
int auxRow;
int diagCarry=0;
int rowLimit=partialResult.length-1;
int colLimit=partialResult[0].length-1;
int initialRow=1;
int colIndex=0;
for (int row=initialRow;row<=rowLimit;row++){
diagonal2Acum=0;
diagonal2Acum +=lastCarry;
lastCarry=0;
auxRow = row;
colIndex=0;
// partialResult[auxRow][]
while ((auxRow<=rowLimit) && (colIndex<=colLimit)){
diagonal2Acum+= partialResult[auxRow++][colIndex++];
}
if ((colIndex==0)&&(row==rowLimit)) {
copyDigit=(diagonal2Acum+carryDigit)%10;
carryDigit=(diagonal2Acum+carryDigit)/10;
multResult.add(copyDigit);
multResult.add(carryDigit);
}
else {
copyDigit=(diagonal2Acum+carryDigit)%10;
carryDigit=(diagonal2Acum+carryDigit)/10;
multResult.add(copyDigit);
}
} // end row for
StringBuilder appended = new StringBuilder();
for (int i=multResult.size()-1;i>=0;i--){
appended.append(multResult.get(i));
}
System.out.println("result is " + appended.toString());
BigInteger the_result1 = new BigInteger(appended.toString());
return the_result1;
}
Assume your partialResult dimensions are width and height you can add by the following two loops (see it here in action):
int digit = width + height - 1;
int carry = 0;
for (int d1 = width - 1; d1 >= 0; d1--) {
for (int r = 0; r < height && d1 + r < width; r++)
carry += partialResult[r][d1 + r];
result[--digit] = carry % 10;
carry /= 10;
}
for (int d2 = 1; d2 < height; d2++) {
for (int c = 0; c < width && d2 + c < height; c++)
carry += partialResult[d2 + c][c];
result[--digit] = carry % 10;
carry /= 10;
}
Note: Carry may be non-empty at the end meaning another digit before the first one in result.

Categories

Resources