I am writing a code to convert a number to binary representation.Here's my code.It doesn't give the correct answer but I can't figure out where I am making the mistake.If someone could point out where my mistake and how to correct it I would be grateful.
public class ConvertBinary{
public static String convertBinary(int n){
String s="";
while(n>0){
s+=(n%2);
n=n/2;
}
int len=s.length();
String[] binary=s.split("");
String[] binaryCopy=new String[s.length()];
for(int i=0;i<len;i++){
binaryCopy[i]=binary[len-i-1];
s+=binaryCopy[i];
}
return s;
}
public static void main (String args[]){
System.out.println(convertBinary(19));
}
}
Apart from all these answers the problem with your code was that you are not clearing the string before reversing it. So before the for loop just put s = "" and you code should work fine.. :)
Based on comment
public class ConvertBinary {
public static String convertBinary(int n) {
String s = "";
while (n > 0) {
s += (n % 2);
n = n / 2;
}
int len = s.length();
String[] binary = s.split("");
String[] binaryCopy = new String[s.length()];
s = "";
for (int i = 0; i < len; i++) {
binaryCopy[i] = binary[len - i - 1];
s += binaryCopy[i];
}
return s;
}
public static void main(String args[]) {
int num = 4;
System.out.println(convertBinary(num));
System.out.println(Integer.toBinaryString(num));
}
}
public static String convertBinary(int n){
String s="";
while(n>0){
s+=(n%2);
n=n/2;
}
return (new StringBuffer(s).reverse().toString());
}
If you're looking for error in your implementation, you'd rather put:
s = (n % 2) + s;
isntead of
s+=(n%2);
so the code'll be
// n should be positive
public static String convertBinary(int n){
if (n == 0)
return "0";
String s = "";
// for is more compact than while here
for (; n > 0; n /= 2)
s = (n % 2) + s;
return s;
}
however in real life
Integer.toString(n, 2);
is much more convenient
Use Java standard library: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString%28int,%20int%29
public class ConvertBinary{
public static String convertBinary(int n){
return Integer.toString(n, 2);
}
public static void main (String args[]){
System.out.println(ConveryBinary.convertBinary(19));
}
}
EDIT: As #Holger says, there's also a toBinaryString: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toBinaryString%28int%29
public static String convertBinary(int n){
return Integer.toBinaryString(n);
}
Related
This is my code to count the number of rotations.
But IDK, What is the problem with it.
Can anyone explain and help me out.
Test Case: Input: david vidda
Output: 2
I tried to have brute force approach but, that wasn't working even.
Can anyone point out my mistake??
import java.util.*;
class solution{
public static int arrayLeftRotation(StringBuilder str1, StringBuilder str2)
{
int i;
int count =0;
for (i = 0; i < str1.length(); i++){
if(str1.equals(str2))
{
count++;
str1 = leftRotatebyOne(str1);
System.out.println(str1);
}
else return count;
}
return count;
}
static StringBuilder leftRotatebyOne(StringBuilder str)
{
int i;
char temp = str.charAt(0);
for (i = 0; i < str.length()-1; i++)
str.setCharAt(str.indexOf(str.charAt(i)+""),str.charAt(i+1));
str.setCharAt(i,temp);
return str;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String strr1= in.nextLine();
StringBuilder str1 = new StringBuilder(strr1);
String strr2 = in.nextLine();
StringBuilder str2 = new StringBuilder(strr2);
System.out.print(arrayLeftRotation(str1, str2));
}
}
Your method leftRotateByOne appears more complicated than necessary.
Try this:
public class Solution
{
public static int arrayLeftRotation(String str1,
String str2)
{
int nr_rotate;
int counter;
nr_rotate = 0;
for (counter = 0; counter < str1.length(); counter++)
{
if (str1.equals(str2))
return (nr_rotate);
else
{
str1 = leftRotateByOne(str1);
nr_rotate++;
System.out.println(str1);
}
}
// No possible solution
return (-1);
} // arrayLeftRotation
public static String leftRotateByOne(String str)
{
return (str.substring(1) + str.charAt(0));
}
public static void main(String[] args)
{
String str1 = "david";
String str2 = "vidda";
System.out.print(arrayLeftRotation(str1, str2));
}
} // class Solution
Another possible solution for arrayLeftRotation,
public static int arrayLeftRotation(String str1, String str2) {
StringBuilder builder = new StringBuilder(str1);
for (int i = 0; i < str1.length(); i++) {
builder.append(str1.charAt(i)).delete(0, 1);
if (str2.equals(builder.toString())) {
return i + 1;
}
}
return -1;
}
Note: this will return -1 if no matches found.
The trick is to append the input string to itself, then call String#indexOf. It will give you the index at which the doubled string contains the expected string, which is what you're looking for.
Example:
public static int numberOfRotations(String input, String expected) {
final String doubledInput = input + input;
return doubledInput.indexOf(expected);
}
If you really want to implement it yourself, you need to simplify your code to minimize the possibility of making mistakes.
public static String rotate(String input) {
return input.substring(1) + input.charAt(0);
}
public static int numberOfRotations(String input, String expected) {
// handle edge cases (null, empty, etc.) here
String rotatedInput = input;
int count = 0;
while (!rotatedInput.equals(expected) && count < input.length()) {
rotatedInput = rotate(rotatedInput);
count++;
}
return count == input.length() ? -1 : count;
}
I am just trying to point out where your error lies and fix it.
Your error lies here in your leftRotatebyOne:
for (i = 0; i < str.length()-1; i++)
str.setCharAt(str.indexOf(str.charAt(i)+""),str.charAt(i+1)); // your error while shifting to the left;
What you are trying to do is shifting one position to the left, and you should just do it as:
for (i = 0; i < str.length()-1; i++)
str.setCharAt(i,str.charAt(i+1));
And then your method will work.
But I have to say Alex M has provided a cleaner solution to your problem. Perhaps you should have a try.
Your solution then can be (after the fix):
public class RotationCount {
public static int arrayLeftRotation(StringBuilder str1, StringBuilder str2) {
int i;
int count = 0;
for (i = 0; i < str1.length(); i++) {
if (!str1.toString().equals(str2.toString())) {
count++;
str1 = leftRotatebyOne(str1);
} else return count;
}
return count;
}
static StringBuilder leftRotatebyOne(StringBuilder str) {
int i;
char temp = str.charAt(0);
for (i = 0; i < str.length() - 1; i++) {
str.setCharAt(i, str.charAt(i + 1));
}
str.setCharAt(i, temp);
return str;
}
public static void main(String[] args) {
StringBuilder str1 = new StringBuilder("david");
StringBuilder str2 = new StringBuilder("vidda");
System.out.print(arrayLeftRotation(str1, str2));
}
}
I am doing one coding question in which I try to decrypt the input string. The procedure for the decryption is:
from 0 to 9 it represent alphabets from a to i.
then 10# represent j, 11# represent k and so.
import java.util.HashMap;
public class Julia {
public static void main(String[] args) {
String s="10#21#12#91";
Julia obj=new Julia();
String result=obj.decrypt(s);
System.out.println(result);
}
public String decrypt(String msg)
{
HashMap<String,Character> hs=new HashMap<>();
hs.put("1",'a');
hs.put("2",'b');
hs.put("3",'c');
hs.put("4",'d');
hs.put("5",'e');
hs.put("6",'f');
hs.put("7",'g');
hs.put("8",'h');
hs.put("9",'i');
hs.put("10",'j');
hs.put("11",'k');
hs.put("12",'l');
hs.put("13",'m');
hs.put("14",'n');
hs.put("15",'o');
hs.put("16",'p');
hs.put("17",'q');
hs.put("18",'r');
hs.put("19",'s');
hs.put("20",'t');
hs.put("21",'u');
hs.put("22",'v');
hs.put("23",'w');
hs.put("24",'x');
hs.put("25",'y');
hs.put("26",'x');
StringBuilder n=new StringBuilder();
for(int i=msg.length()-1;i>=0;i--)
{
if(msg.charAt(i)=='#' && i>=2)
{
StringBuilder s=new StringBuilder().append(msg.charAt(i-2)).append(msg.charAt(i-1));
System.out.println(s);
n.append(hs.get(s));
System.out.println(n);
i=i-2;
}
else
{
n.append(hs.get(msg.charAt(i)));
}
}
return n.toString();
}
}
That is code I wrote. But the output I am getting is nullnullnullnullnull.
I think the issue is with StringBuilder. Can anyone help me with that and explain the concept? If someone has better solution please guide.
You should not use data (a map) when you could have used a simple formula.
My suggestion:
import java.util.ArrayList;
import java.util.List;
public final class Julia {
public static void main(final String[] args) {
final String s = "10#21#12#91";
final String result = decrypt(s);
System.out.println(result);
}
private static String decrypt(final String s) {
final List<Integer> crypt = new ArrayList<>();
final String[] groups = s.split("#");
for (int i = 0; i < groups.length; i++) {
final String group = groups[i];
int j = 0;
// Special case for last group
if ((i == (groups.length - 1)) && !s.endsWith("#")) {
j = group.length();
}
if (group.length() > 2) {
j = group.length() - 2;
}
for (int k = 0; k < j; k++) {
crypt.add(Integer.valueOf(group.substring(k, k + 1)));
}
if (j < group.length()) {
crypt.add(Integer.valueOf(group.substring(j, group.length())));
}
}
final StringBuilder n = new StringBuilder(crypt.size());
for (final Integer c : crypt) {
final char d = (char) (('a' + c) - 1);
n.append(d);
}
return n.toString();
}
}
Please note that there are two mistakes in the question: The letter a is 1, not zero, and the value for 26 is z, not x. The latter error is typical when you use data where a formula would do.
Since you are learning, I would note that the decrypt methods - both my suggestion and yours - should be static since they do not use any fields, so the instantiation is not necessary.
This is Pattern Matching problem which can be solved by Regex.
Your code has some bugs and those are already pointed out by others. I don't see any solution which looks better than a simple regex solution.
Below regex code will output 'julia' for input '10#21#12#91'.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Julia {
public static void main(String[] args) {
String s="10#21#12#91";
Julia obj=new Julia();
String result=obj.decrypt(s);
System.out.println(result);
}
public String decrypt(String msg)
{
Pattern regex = Pattern.compile("((\\d\\d#)|(\\d))");
Matcher regexMatcher = regex.matcher(msg);
StringBuffer result = new StringBuffer();
while (regexMatcher.find())
regexMatcher.appendReplacement(result, getCharForNumber(Integer.parseInt(regexMatcher.group(1).replace("#",""))));
return result.toString();
}
private String getCharForNumber(int i) {
return i > 0 && i < 27 ? String.valueOf((char)(i + 96)) : null;
}
}
I hope it helps.
hs.get(s) will always return null, since s is not a String.
Try hs.get(s.toString())
hs.get(msg.charAt(i)) will also always return null, since you are passing a char to get instead of String.
There may also be logic problems in your code, but it's hard to tell.
Optimized version of your code
public class Main {
public static void main(String[] args) {
String cipher = "10#21#12#91";
System.out.print(decrypt(cipher));
//output : julia
}
static String decrypt(String cipher) {
//split with # to obtain array of code in string array
String[] cipher_char_codes = cipher.split("#");
//create empty message
StringBuilder message = new StringBuilder();
//loop for each code
for (String code : cipher_char_codes) {
//get index of character
int index = Integer.parseInt(code);
if (index > 26) {
char[] pair = code.toCharArray();
for (int i = 0; i < pair.length; i++) {
int x = Integer.parseInt("" + code.charAt(i));
message.append((char) ('a' + ((x - 1) % 26)));
}
} else {
//map index into 1 to 26
//find ascii code and cast into char
message.append((char) ('a' + ((index - 1) % 26)));
}
}
return message.toString();
}
}
Regex is indeed the way to go, and the code proposed by Pirate_Jack can be improved. It calls the expensive regex two superfluous times (replace is a regex operation).
Following is a yet improved version:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class Julia3 {
public static void main(final String[] args) {
final String s = "10#21#12#91";
final String result = decrypt(s);
System.out.println(result);
}
public static String decrypt(final String msg) {
final Pattern regex = Pattern.compile("((\\d\\d)(#)|(\\d))");
final Matcher regexMatcher = regex.matcher(msg);
final StringBuffer result = new StringBuffer();
String c;
while (regexMatcher.find()) {
if (regexMatcher.group(2) == null) {
c = regexMatcher.group(1);
} else {
c = regexMatcher.group(2);
}
result.append((char) ((Integer.parseInt(c) + 'a') - 1));
}
return result.toString();
}
}
This is not right :
hs.get(s)
s is a StringBuilder. It should be hs.get(Char)
Edit: an optional different solution:
public class Julia {
public static void main(String[] args) {
String s="10#21#12#91";
List<String> numbers = splitToNumbers(s);
Julia obj=new Julia();
String result=obj.decrypt(numbers);
System.out.println(result);
}
/**
*#param s
*#return
*/
private static List<String> splitToNumbers(String s) {
//add check s is not null
char[] chars = s.toCharArray();
char delimiter = '#';
List<String> numberAsStrings = new ArrayList<String>();
int charIndex = 0;
while (charIndex < (chars.length -3)) {
char theirdChar = chars[charIndex+2];
if(theirdChar == delimiter) {
numberAsStrings.add(""+chars[charIndex]+chars[charIndex+1]);
charIndex +=3;
}else {
numberAsStrings.add(""+chars[charIndex]);
charIndex ++;
}
}
//add what's left
while (charIndex < chars.length) {
numberAsStrings.add(""+chars[charIndex]);
charIndex++;
}
return numberAsStrings;
}
public String decrypt(List<String> numbersAsStings){
StringBuilder sb=new StringBuilder();
for (String number : numbersAsStings) {
int num = Integer.valueOf(number);
sb.append(intToChar(num-1));
}
return sb.toString();
}
private char intToChar(int num) {
if((num<0) || (num>25) ) {
return '?' ;
}
return (char)('a' + num);
}
}
I am writing a code to reverse a number entered by a user using java. I am using an array for this purpose. The problem that I am facing is in returning the array when I call my method in the main function.
I understand that you want to reverse an array... so, for that you can use ArrayUtils.reverse
ArrayUtils.reverse(int[] array)
For example, you can do:
public static void main(String[] arg){
int[] arr = { 1,2,3,4,5,6};
ArrayUtils.reverse(arr);
System.out.println(Arrays.toString(arr));
// Prints: [6, 5, 4, 3, 2, 1]
}
However, if you want to code the reverse by yourself, if you check the source code of ArrayUtils.reverse, you can find how Apache guys did it. Here the implementation:
public static void reverse(int[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
int tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
There are many ways of doing it. Depends if you want to use Java Builtin methods or not. Here is my part:
Reverse a int array using ListIterator:
public class ReverseAListWithoutInbuiltMethods {
public static void main(String[] args) {
int[] arr={12, 4, 34, 7, 78,33, 20};
display(arr);
int[] rev=reverse(arr);
display(rev);
}
private static void display(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.print(" "+arr[i]);
}
System.out.println("");
}
private static int[] reverse(int[] arr){
List<Integer> list=new ArrayList<Integer>();
for(int a:arr){
list.add(a);
}
int[] rev=new int[arr.length];
int j=0;
ListIterator<Integer> listI=list.listIterator(arr.length);
while(listI.hasPrevious()){
rev[j]=listI.previous();
j++;
}
return rev;
}
}
Reverse by for loop only:
public static void main(String[] args) {
/* create a new string */
StringBuilder s = new StringBuilder("GeeksQuiz");
System.out.println(" ************* REVERSED STRING IS **************");
char[] c2=reverseForLoop(s);
for (int i = 0; i < c2.length; i++) {
System.out.print(c2[i]);
}
}
private static char[] reverseForLoop(StringBuilder sb) {
char[] str = sb.toString().toCharArray();
int n = str.length;
char[] charNew = new char[n];
int j = 0;
for (int i = n - 1; i >= 0; i--) {
charNew[j] = str[i];
j++;
}
return charNew;
}
Reverse using swap method:
private static char[] reverse2(StringBuffer sb) {
char[] str=sb.toString().toCharArray();
int n = str.length;
for (int i = 0; i < n / 2; i++) {
swap(str, i, n - 1 - i);
}
return str;
}
private static void swap(char[] charA, int a, int b) {
char temp = charA[a];
charA[a] = charA[b];
charA[b] = temp;
}
Reverse String using Stack implementation:
public class StackForStringReverse {
public static void main(String[] args) {
/*create a new string */
StringBuffer s= new StringBuffer("GeeksQuiz");
/*call reverse method*/
reverse(s);
/*print the reversed string*/
System.out.println("Reversed string is " + s);
}
private static void reverse(StringBuffer str) {
int n=str.length();
MyStack obj=new MyStack(n);
// Push all characters of string
// to stack
int i;
for (i = 0; i < n; i++)
obj.push(str.charAt(i));
// Pop all characters of string and put them back to str
for (i = 0; i < n; i++)
{
char ch = obj.pop();
str.setCharAt(i,ch);
}
}
}
class MyStack{
int size;
char[] a;
int top;
public MyStack(int n) {
top=-1;
size=n;
a=new char[size];//{'1','f','f','f'};
}
public boolean isEmpty() {
return top<0;
}
/**
* Insert data into Stack if it's not full*/
public void push(char c) throws IllegalArgumentException{
if(top>=size) {
throw new IllegalArgumentException("Stack overflow.");
}
a[++top]=c;
}
public char pop() {
if(top<0) {
throw new IllegalArgumentException("Stack underflow.");
}
char x=a[top--];
return x;
}
public void clear() {
while(top>0) {
top--;
size=top;
}
}
/**
* Display the data inserted */
public void display() {
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]);
}
System.out.println("");
}
}
You can do that using StringBuilder :
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println(getReverse(s.nextInt()));
}
public static int getReverse(int a){
StringBuilder sb = new StringBuilder();
sb.append(String.valueOf(a));
sb = sb.reverse();
return Integer.parseInt(sb.reverse().toString());
}
}
StringBuilder can do reversals.
String reverseNumber(Number n) {
String numStr = n.toString();
StringBuilder reverser = new StringBuilder(numStr);
reverser.reverse();
return reverser.toString();
}
Obviously there are some gaps here for particular cases (e.g. negative numbers) but I'll leave that for you to solve. This should serve as a good starting point.
Java is powerful, but complicated.
Here is a oneliner for it.
public static void main(String[] args) {
int n = 123;
int reversed_n = (int) Integer.valueOf( // 5.) cast back to an int.
new StringBuilder(
Integer.toString(n) // 1.) Make the integer a String.
) // 2.) load that string to a String builder.
.reverse() // 3.) reverse the string.
.toString())); // 4.) go back to a string.
}
Tried my hand at a relatively well-documented, external library and array-free solution. Hope it helps!
int reverseNumber(int inputNum)
{
String numString = Integer.toString(inputNum);
int numLength = numString.length();
int finalReversedNumber = 0;
/*
* Goes through the input number backwards, and adds the digit (with it's new value) to the final number.
* This is accomplished by multiplying the current number by 10 to the power of the index i, which corresponds
* to the current digit value of the number.
* i the index counter, goes from the length of the input number (not inclusive) to 0 (inclusive)
*/
for(int i=numLength-1; i>=0; i--)
{
int currentNum = Integer.parseInt(String.valueOf(numString.charAt(i)));
int valueInFinalNum = currentNum * (int)Math.pow(10, i); // i.e. a 5 in the thousands digit is actually 5000
finalReversedNumber += valueInFinalNum;
}
return finalReversedNumber;
}
I am very new to programming and I have to write a method and program for the following; public static String repeat(String str, int n) that returns the string repeated n times. Example ("ho", 3) returns "hohoho" Here is my program so far:
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.nextLine();
System.out.println(repeat (str));//Having trouble with this line
}
// **TEST PROGRAM**//
public static String repeat(String str, int n)
{
if (n <= 0)
{
return ""//Having trouble with this line
}
else if (n % 2 == 0)
{
return repeat(str+str, n/2);
}
else
{
return str + repeat(str+str, n/2);
}
}
}
I made some changes to my code, but it still is not working
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.nextLine();
int n = in.nextInt();
System.out.println(repeat(str,n));
}
// **TEST PROGRAM**//
public static String repeat(String str, int n)
{
if (n <= 0)
{
return "";
}
else if (n % 2 == 0)
{
return repeat(str+str, n/2);
}
else
{
return str + repeat(str+str, n/2);
}
}
}
You've missed a semi colon on the line you're having trouble with, it should be return ""; and not return ""
Also, the line System.out.println(repeat (str)); should have 2 arguments because you're repeat definition is:
public static String repeat(String str, int n)
As a further note, an easier function might be
public static String repeat(String str, int n)
{
if (n == 0) return "";
String return_str = "";
for (int i = 0; i < n; i++)
{
return_str += str;
}
return return_str;
}
public static String repeat(String toRepeat, int n){
if(n==0){
return "";
}
return toRepeat+repeat(toRepeat,n-1);
}
2 things I noticed quickly: you forgot a semi-column and your call of "repeat" doesn't match the method signature (you forgot n)
You are not passing correct arguments while you calling the desired method.
Call as repeat (str,k) k - should be an integer
I want to generate all possible teams of a group of n things taken k at a time, for example "abcd" = ab,ac,ad... without duplicates. I have written this, but it generates all permutations of a string. I have written a method to check if two strings have the same characters, but I don't know if this is the correct way.
package recursion;
import java.util.Arrays;
public class Permutations2 {
public static void main(String[] args) {
perm1("", "abcd");
System.out.println(sameChars("kostas","kstosa"));
}
private static void perm1(String prefix, String s) {
int N = s.length();
if (N == 0){
System.out.println(prefix);
}
else {
for (int i = 0; i < N; i++) {
perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
}
}
}
private static boolean sameChars(String firstStr, String secondStr) {
char[] first = firstStr.toCharArray();
char[] second = secondStr.toCharArray();
Arrays.sort(first);
Arrays.sort(second);
return Arrays.equals(first, second);
}
}
You are describing a power set.
Guava has an implementation.
May you want the Enumerating k-combinations.
private static void combinate(String s, String prefix, int k) {
if (s.length() < k) {
return;
} else if (k == 0) {
System.out.println(prefix);
} else {
combinate(s.substring(1), prefix + s.charAt(0), k - 1);
combinate(s.substring(1), prefix, k);
}
}
public static void main(String[] args) {
combinate("abcd", "", 2);
}
Output:
ab
ac
ad
bc
bd
cd
See Introduction to Programming in Java - Recursion - Robert Sedgewick and Kevin Wayne
This should work without recursion:
private static void perm(String s) {
char[] arr = s.toCharArray();
for (int i = 0; i < s.length() - 1; i++) {
for(int j = i + 1; j < s.length(); j++) {
System.out.println(String.valueOf(arr[i]) + String.valueOf(arr[j]));
}
}
}
It's O(n**2).