This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 8 years ago.
I want to reverse an inputted number. I've written the code for it. But i need to know if it could have been done in any other much faster way. Please feel free to modify my code.
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number");
int num=Integer.parseInt(in.readLine());
int no=num;
int d;
int rev_no=0;
int digits=0;
while(num>0)
{
num/=10;
digits++;
}
while(no>0)
{
d=no%10;
rev_no+=d*(Math.pow(10,(digits-1)));
no/=10;
digits--;
}
System.out.println(rev_no);
}
As #Christian mentioned above in the comments, you can do something like this:
int originalInt = 123456789;
String str = new StringBuilder(Integer.toString(originalInt)).reverse().toString();
int reversedInt = Integer.parseInt(str);
Or as a one-liner:
Integer.parseInt(new StringBuilder(Integer.toString(new Integer(123456789))).reverse().toString());
EDIT:
To answer #Luiggi Mendoza's concern - supporting numbers that are too big to fit an Integer can be done using BigInteger as follows:
BigInteger originalValue = BigInteger.valueOf(563463346233535772l);
String reversedString = new StringBuilder(originalValue.toString()).reverse().toString();
String myNum=num.toString();
String reversed = new StringBuffer(myNum).reverse().toString();
num=Integer.parseInt(reversed);
Example without StringBuilder.
private static long revert(long number){
String numberAsString = String.valueOf(number);
String[] splitted = numberAsString.split("");
String returnString = "";
for(int i = splitted.length-1; i >=0; i--){
returnString += splitted[i];
}
return Integer.valueOf(returnString);
}
Related
I am trying to write my own string reverse algorithm (I know this already exists in java but I am doing this for education). The code below is what I have so far. It outputs only half the string reversed. I have done some debugging and the reason is that it is changing stringChars2 at the same time as stringChars but I have no idea why that is happening as I am only trying to change stringChars. All help greatly appreciated.
EDIT my question was not "how to reverse a string" which has been asked before... but why my objects where changing without instruction, the answer below completely explains the problem.
public static void main(String[] args) {
//declare variables
Scanner input = new Scanner(System.in);
String myString = "";
int length = 0, index = 0, index2 = 0;
//get input string
System.out.print("Enter the string you want to reverse: ");
myString = input.next();
//find length of string
length = myString.length()-1;
index2 = length;
//convert to array
char[] stringChars = myString.toCharArray();
char[] stringChars2 = stringChars;
//loop through and reverse order
while (index<length) {
stringChars[index] = stringChars2[index2];
index++;
index2--;
}
//convert back to string
String newString = new String(stringChars);
//output result
System.out.println(newString);
//close resources
input.close();
}
char[] stringChars = myString.toCharArray();
char[] stringChars2 = stringChars;
On the second line you are assigning stringChars2 to the same object as stringChars so basically they are one and the same and when you change the first you are changing the second as well.
Try something like this instead:
char[] stringChars = myString.toCharArray();
char[] stringChars2 = myString.toCharArray();
You can read more about it here
All that is not necessary.
You can simply reverse a string with a for loop (in a method):
public String reverseString(String str)
{
String output = "";
int len = str.length();
for(int k = 1; k <= str.length(); k++, len--)
{
output += str.substring(len-1,len);
}
return output;
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 5 years ago.
public static void main (String args[]) {
Scanner io = new Scanner(System.in);
int a = io.nextInt();
io.nextLine();
for(int i = 0; i < a; i++ ) {
String input = io.nextLine();
String[] splitArr = input.split("\\s+");
int p[] = new int[input.length()];
int q = 0;
for (String par : splitArr) {
System.out.println(par);
p[q++] = Integer.parseInt(par);
System.out.println(p);
}
Sort(p);
}
}
The input: 2 121213
Output: 121213 [I#1f96302
The last line shows the array stored in p[]. That is incorrect. Help someone!
Your print line is incorrect, your print line should be:
System.out.println(Arrays.toString(p));
You also increment q in a wrong way, your increment code should be like:
p[q] = Integer.parseInt(par);
q++;
System.out.println(p);
I'm having trouble with this problem.
Here is the code I wrote out:
package com.jdewey.rvrs;
import java.util.Scanner;
public class Reverse {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter your string: ");
String userIn = console.nextLine();
int inLength = userIn.length();
stringRvrs(userIn, inLength);
}
public static void stringRvrs(String x, int length){
for(int i = 1; i <= length; i++){
int y = -1 * i + length;
System.out.print(x.substring(y));;
}
}
}
It's supposed to output "tset" if you were to input "test"
Please help!
It makes more sense to just write your loop to start at the end of the string, and also to print each character using charAt instead of substring. See below:
public static void stringRvrs(String x, int length){
String result = "";
for(int i = length - 1; i >= 0; i--){
result = result + x.charAt(i);
}
System.out.println(result);
}
Of course, there is an easier way using library functions to reverse a string (see here: Reverse a string in Java), but I assume this is a learning exercise for you so I corrected the code instead of just linking to an easy way to do it.
Try StringBuilder as in:
public static void stringRvrs(String x){
char [] all = x.toCharArray();
StringBuilder concate = new StringBuilder();
for(int i = all.length-1;i >= 0;i--){
concate = concate.append(String.valueOf(all[i]));
}
System.out.println(x+" reversed to "+concate);
}
No need to pass int length as an parameter to the method.
you can simply use stringBuilder.reverse();
your method should look like this after the changes,
public static void stringRvrs(String x, int length){
StringBuilder sb = new StringBuilder(x);
System.out.println(sb.reverse());
}
There is no need to pass the length of the String as an argument since it can be found using string.length(); at any point of time.
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
I am trying to break down a long given string into a smaller string of given length x, and it returns an array of these small strings. But I couldn't print out, it gives me error [Ljava.lang.String;#6d06d69c
Please take a look at my code and help me out if I am doing wrong. Thanks so much!
public static String[] splitByNumber(String str, int num) {
int inLength = str.length();
int arrayLength = inLength / num;
int left=inLength%num;
if(left>0){++arrayLength;}
String ar[] = new String[arrayLength];
String tempText=str;
for (int x = 0; x < arrayLength; ++x) {
if(tempText.length()>num){
ar[x]=tempText.substring(0, num);
tempText=tempText.substring(num);
}else{
ar[x]=tempText;
}
}
return ar;
}
public static void main(String[] args) {
String[] str = splitByNumber("This is a test", 4);
System.out.println(str);
}
You're printing the array itself. You want to print the elements.
String[] str = splitByNumber("This is a test", 4);
for (String s : str) {
System.out.println(s);
}
This question already has answers here:
How to generate a random alpha-numeric string
(46 answers)
Closed 9 years ago.
I am using String Builder from another answer, but I can't use anything but alpha/numeric, no whitespace, punctuation, etc. Can you explain how to limit the character set in this code? Also, how do I insure it is ALWAYS 30 characters long?
Random generator = new Random();
StringBuilder stringBuilder = new StringBuilder();
int Length = 30;
char tempChar ;
for (int i = 0; i < Length; i++){
tempChar = (char) (generator.nextInt(96) + 32);
stringBuilder.append(tempChar);
I have looked at most of the other answers, and can't figure out a solution to this.
Thanks. Don't yell at me if this is a duplicate. Most of the answers don't explain which part of the code controls how long the generated number is or where to adjust the character set.
I also tried stringBuilder.Replace(' ', '1'), which might have worked, but eclipse says there is no method for Replace for StringBuilder.
If you want to control the characterset and length take for example
public static String randomString(char[] characterSet, int length) {
Random random = new SecureRandom();
char[] result = new char[length];
for (int i = 0; i < result.length; i++) {
// picks a random index out of character set > random character
int randomCharIndex = random.nextInt(characterSet.length);
result[i] = characterSet[randomCharIndex];
}
return new String(result);
}
and combine with
char[] CHARSET_AZ_09 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
to specify the characterset.
It's not based on StringBuilder since you know the length and don't need all the overhead.
It allocates a char[] array of the correct size, then fills each cell in that array with a randomly chosen character from the input array.
more example use here: http://ideone.com/xvIZcd
Here's what I use:
public static String randomStringOfLength(int length) {
StringBuffer buffer = new StringBuffer();
while (buffer.length() < length) {
buffer.append(uuidString());
}
//this part controls the length of the returned string
return buffer.substring(0, length);
}
private static String uuidString() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
You may try this:
//piece
int i = 0;
while(i < length){
char temp =(char) (generator.nextInt(92)+32);
if(Character.isLetterOrDigit(temp))
{
stringBuilder.append(temp);
++i;
}
}
System.out.println(stringBuilder);
Should achieve your goal