haw can i flip an integer at a certain index
for example i have this number 1001 and i need to flip it starting from index 2
the result is going to be 1010
here is what i tried any easier ways?
public class TEST {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int code = scan.nextInt();
int index = scan.nextInt();
String s = code + "";
String f = "";
for (int i = s.length() - 1; i >= index; i--) {
f += s.charAt(i);
}
for (int i = 0; i < index; i++) {
f += s.charAt(i);
}
System.out.println(f);
}
}
Another question is that haw i shift every digit to the left for example if i have 1001 it will become 1100
You could use the reverse() method of the StringBuilder class to reverse the number and then parse it back as an integer. Use the StringBuilder as follows:
StringBuilder num = new StringBuilder("1234");
num.reverse(); // is now "4321"
To parse the integer:
int i = Integer.parseInt(num.toString());
I believe this is what you are looking for. This assumes you are using a 0-indexed system for choosing where the reversal starts.
Scanner scan = new Scanner(System.in);
int code = scan.nextInt();
int index = scan.nextInt();
String s = code + "";
String f = s.substring(0, index);
for(int i = index; i < s.length(); i++)
f += s.charAt(s.length() - (i - index) - 1);
System.out.println(f);
Your flip operation if I assume that you mean that a string such as 12345 consists of indices [1,2,3,4,5] rather than [0,1,2,3,4]˙ and starting from index of 1 is inclusive flip from 1 to 5, and your operation goes from left to right, then you can do the following
int index = 1;
String number = "12345";
String subnumber = number.substring(index - 1); //first index, 0th character
String reversedNumber = new StringBuilder(subnumber).reverse().toString();
String result = number.substring(0, index - 1) + reversedNumber;
System.out.println(result); //54321
Of course, if it was supposed to from right to left, then you need to mess with the length of the String and mirror the operations...
Related
Example:
If i give a number 12345 , i should get an answer like 15243
in the same way if it is 123456 , i should get 162534
i have already tried getting the first value and appending the last value using reverse technique
public class MyFirstJavaProgram {
public static void main(String []args) {
String str = "12345";
String val = str;
char a;
int num=0;
int d=0;
int n;
for(int i=0; i<=str.length()/2; i++) {
a = str.charAt(i);
num = num*10+Character.getNumericValue(a);
if(Integer.parseInt(str)!=0){
d=Integer.parseInt(str)%10;
num = num*10+d;
n=Integer.parseInt(str)/10;
str = Integer.toString(n);
}
}
System.out.println(num);
}
}
i should get the result if they give even number or odd number
Without doing what is presumably homework for you, imagine you have a loop in which there are two integer variables a and b. Variables a and b are string indexes.
You are taking characters from the string at positions a,b,a,b,a,b etc.
BUT the values of a and b need to change for each iteration. If the length of the String is n, a will follow the sequence 0,1,2,3... and b will follow the sequence (n-1),(n-2),(n-3) etc
The loop should continue while a < b.
This is my solution for your exercise:
Method parameter "A" is Integer number you want to parse.
First you create Char Array from given number and then iterate through it. If i%2 == 0 it means that you take number from beginning otherwise from the end
public static int algorithm(int A) {
StringBuilder shuffleNumber = new StringBuilder();
char[] numbersArray = Integer.toString(A).toCharArray();
for (int i = 0; i < numbersArray.length; i++) {
if (i % 2 == 0)
shuffleNumber.append(numbersArray[i / 2]);
else
shuffleNumber.append(numbersArray[numbersArray.length - i / 2 - 1]);
}
return Integer.parseInt(shuffleNumber.toString());
}
If you want a solution without string methods, there is a not so complicated one:
public static void main(String[] args) throws IOException {
String str = "1234567";
int len = str.length();
int num=0;
char a;
for(int i = 0; i < len / 2; i++) {
a = str.charAt(i);
num = num * 10 + Character.getNumericValue(a);
a = str.charAt(len -1 - i);
num = num * 10 + Character.getNumericValue(a);
}
if (len % 2 == 1) {
a = str.charAt(str.length() / 2);
num = num * 10 + Character.getNumericValue(a);
}
System.out.println(num);
}
will print
1726354
Check the last if that takes care the case of odd number of digits in the number.
public class MyFirstJavaProgram {
public static void main(String []args) {
String str = "12345678";
int val = str.length();
char a;
int num=0;
int d=0;
int n;
for(int i=0; i<=str.length()-2; i++)
{
a = str.charAt(i);
num = num*10+Character.getNumericValue(a);
if(Integer.parseInt(str)!=0)
{
d=Integer.parseInt(str)%10;
num = num*10+d;
n=Integer.parseInt(str)/10;
str = Integer.toString( n );
}
}
if(val%2!=0)
{
num = num*10+Integer.parseInt(str)%10;
System.out.println(num);
}
else{System.out.println(num);}
}
}
this is working for my question... Thanks all
Following is my solution -
public static void solution(String s) {
StringBuffer st = new StringBuffer();
for (int i = 0; i < s.length() / 2; i++) {
st.append(s.charAt(i));
st.append(s.charAt(s.length() - 1 - i)); // appending characters from last
}
if (s.length() % 2 != 0) {
st.append(s.charAt(s.length() / 2));
}
System.out.println(Integer.parseInt(st.toString()));
}
my logic is to keep appending first and last character to new string till i < s.length/2.
If string is of odd length , it means only last character is remaining, append it to your resultant string.
Else , no character is left and you have your complete string.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < 4; i++)
{
int number = input.nextInt();
int reverse = 0;
while (number != 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
System.out.println(reverse);
}
}
}
All numbers reverse well but I have problem with reversing numbers that end with zero e.g numbers like 10000 instead of reversing result being 00001 it gives the result as 1 which is not what the question wants is there a way to use integers or string will be the best and easier approach? Thank you
Try the reversing of string concept
String s ="10000";
String n= "";
for(int i=0; i<s.length(); i++){
n = s.charAt(i) + n;
}
System.out.println(n);
You can create a variable length, and use System.out.printf to format output.
With %0 + length + d, it will add 0 on the left to make the output have this length.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < 4; i++)
{
int number = input.nextInt();
int reverse = 0;
int length = String.valueOf(number).length();
while (number != 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
System.out.printf("%0" + length + "d", reverse);
}
}
}
You could also solve it with a StringBuilder. It already has a method called reverse:
public String reverseInput(int number) {
String s = Integer.toString(number);
return new StringBuilder(s).reverse().toString();
}
You can't have a Integer beginning with 0 except 0 itself. So you will have to work with Strings or other datastructures.
I'm working on an assignment for one of my classes. I'm very new to java in general and for this problem I was asked to only use loops and the charAt(); command to reverse the midpoint of a string. However, I came to an issue when I try to reverse the string after the midpoint. It gave me an exception and I don't know how to make of it since it looks correct to me. Any help would be appreciated.
import java.util.Scanner;
public class PS4Reverse {
public static void main (String [] args) {
String x = "";
String t = "";
String full = "";
String rev = "";
String complete = "";
Scanner user = new Scanner(System.in);
System.out.println("Enter a string.");
x = user.nextLine();
int real = x.length();
int half = x.length();
half = half / 2;
int i = 0;
for (i = 0; i != half; i++)
{
char n = x.charAt(i);
full = full + n;
}
for (i = i; i != real; i++)
{
char n = x.charAt(i);
t = t + n;
}
int back = t.length();
System.out.println(back);
for (i = back; i != 0; i--)
{
char n = t.charAt(i);
rev = rev + n;
}
complete = full + rev;
System.out.println("Original String:\t\t" + x)
System.out.println("Reverse String:\t\t" + complete);
}
}
Thank all y'all very much in advance!
First of all, it helps if you're exact when telling us what exception is happening. It is a StringIndexOutOfBoundsException, not a String out of Range exception or an indexoutofrangeexception.
Anyway, this is the issue:
int back = t.length();
for (i = back; i != 0; i--)
{
char n = t.charAt(i);
The indexes are zero-baed, so if t.length() is 4, t.charAt(4) is going to be out of bounds. You need to start at t.length() - 1.
You got this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(Unknown Source)
at PS4Reverse.main(PS4Reverse.java:49)
int back = t.length(); // this code length of t string. But array indis is starting 0.
This means first item is 0 , last item must be back-1.
you use that;
for (i = back-1; i >= 0; i--)
{
char n = t.charAt(i);
rev = rev + n;
}
I am trying to make an application that will reverse a string using a while loop. Just wondering if I am on the right path or not.
So I thought I would make a while loop to determine how many chars i should make. Then I would just print them in reverse in the console.
Here is my code so far. Any help would be appreciated.
// Get the text from the input from the user
// Outputs it to the Text area
// Uses while loop to calculate how many chars to create
String Startword = txfInput.getText();
int LengthOfWord = Startword.length();
int Counter = 1;
while (Counter <= LengthOfWord)
{
// Creates amounts of chars based off the counter
Counter = Counter +1 ;
}
Any suggestions?
Just use a for loop..
String reverse = "";
for (int i = word.length()-1; i>=0; i--)
{
reverse += word.charAt(i);
}
if you want a while... then
while(i >= 0)
{
reverse += word.charAt(i);
i--;
}
You just need to add a character to the reverse String after every iteration, like this:
String Startword = txfInput.getText();
String rev="";
int LengthOfWord = Startword.length();
int Counter = 1;
while (Counter <= LengthOfWord)
{
rev=Startword.charAt(Counter-1)+rev; // Add a character to rev.
Counter = Counter +1 ;
}
System.out.println(rev);
Might be easier to do with a char array:
char[] output = new char[Startword.length];
for(int i = 0; i < Startword.length; i++){
output[i] = Startword.charAt(Startword.length - i - 1);
}
String rev = new String(output);
Scanner input = new Scanner(System.in);
String s=input.nextLine();
char[] stringArray;
stringArray = s.toCharArray();
int temp;
int low=0;
int high=stringArray.length-1;
while(low<high){
temp= stringArray[low];
stringArray[low] = stringArray[high];
System.out.print(stringArray[low]);
low ++;
high--;
}
check this out
I've been stuck on this problem for two hours now. Basically I need to reverse a string (which I've done no problem), then swap every nth letter (which is where im stuck).
Here is what I have so far:
public class StringMethods {
public static void main(String[] args) {
String s = "Hey there";
int n = 2;
System.out.println(reverseString(s));
System.out.println(reverseStringChallenge(s, n));
}
private static String reverseString(String s) {
String reversed = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i);
}
return reversed;
}
private static String reverseStringChallenge(String s, int n) {
String reversed = "";
String swapped = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i); // normal reverse
}
char [] charArray = reversed.toCharArray(); //Strings are immutable, convert string to char array
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0) {
//this is where im stuck
}
}
return swapped;
}
}
I know that strings are immutable in java so I need to convert the reversed string into a char array, and then loop through the array but not sure what to do here.
Any advice would be really appreciated. its doing my head in.
Edit: sorry what I mean by swap every nth letter is that say n = 2. then every second letter gets swapped with its previous one.
You didn't clarify the swap logic, but how about something like this:
for(int i = n; i < charArray.length; i += n) {
char a = charArray[i-n];
char b = charArray[n];
charArray[i-n] = b;
charArray[n] = a;
}
Here's a basic swap
int n = 1;
int n1 = 2;
int temp = n; // variable to hold n value
n = n2; // make n = n2
n2 = temp; // make n2 = n
// now n = 2
// and n2 = 1
Not really sure from your question what it is you're trying to do, so I can't really give a definite answer
If you are swapping the current char with the next char you could do something like:
private static String reverseStringChallenge(String s, int n)
{
String reversed = StringUitls.reverse(s);
StringBuilder sb = new StringBuilder();
char [] charArray = reversed.toCharArray();
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0)
{
sb.append(charArray[i+1]).append(charArray[i]);
i++;
}else{
sb.append(charArray[i]);
}
}
return sb.toString();
}
I'm excuse null and out of bound checks =) good luck