I try to convert numbers of a String in to an array with the datatyp char. My problem is, that the number in my array is everytime 48 to high. I also know that the problem has something to do with ASCII table. What can i do to solve this problem?
package Test;
public class Main {
public static void main(String[] args) {
int iNumber = 0; int indexNumber = 0;
String calculation = "5+8";
int lengthCalculation = calculation.length();
int[] number= new int[lengthCalculation/2+1];
while(iNumber < lengthCalculation) {
number[indexNumber] = calculation.charAt(iNumber);;
iNumber+=2;
indexNumber++;
}
for(int q : number) {
System.out.println(q); }
}
}
use
number[indexNumber] = calculation.charAt(iNumber) - '0';
Digit 0 has an ASCII value of 48. The range of ASCII value for 0-9 digits is from 48-57. So, whenever you extract a character, let's say '5', you store 53 instead of 5 in the array. So try to use the below code modification where you subtract character '0':
public static void main(String[] args) {
int iNumber = 0; int indexNumber = 0;
String calculation = "5+8";
int lengthCalculation = calculation.length();
int[] number= new int[lengthCalculation/2+1];
while(iNumber < lengthCalculation) {
number[indexNumber] = calculation.charAt(iNumber)-'0'; //modified
iNumber+=2;
indexNumber++;
}
for(int q : number) {
System.out.println(q); }
}
Related
I'm trying to get a printout of all variations of a certain String. For example, we have this input: AB0C0. The 0 in the 3rd and 5th spots should be treated as variables. The variable characters are 1, 2, and 3 to be placed in the spot of 0. This means there would be all possible variations of this input:
AB1C1
AB2C1
AB3C1
AB1C2
AB1C3
AB2C2
AB2C3
AB3C2
AB3C3
This is just an example. A 5-character long string is a place for 1 to 5 variables. The issue I'm facing is, that it should generate all variations no matter how many variables are in the input in no matter in which place they are.
Scanner scanner = new Scanner (System.in);
System.out.println("Enter the key consisting of 5 characters:");
String input = scanner.next();
String strOutput1 = input.replaceFirst("0","1");
String strOutput1A = input.replace("0","1");
String strOutput2 = input.replaceFirst("0","2");
String strOutput3 = input.replaceFirst("0","3");
String strOutput4 = input.replaceFirst("0","4");
String strOutput5 = input.replaceFirst("0","5");
System.out.println(strOutput1.toUpperCase());
System.out.println(strOutput1A.toUpperCase());
System.out.println(strOutput2.toUpperCase());
System.out.println(strOutput3.toUpperCase());
System.out.println(strOutput4.toUpperCase());
System.out.println(strOutput5.toUpperCase());
What about this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the key consisting of 5 characters:");
String input = scanner.next();
//find positions of '0' in input
List<Integer> varPositions = findVarPositions(input);
//create permutations
List<String> permutations = new ArrayList<>();
permutations.add(input);//AB0C0
for (int position : varPositions) {
permutations = permutateAtPosition(permutations, position);
}
//print permutations
for (String permutation : permutations) {
System.out.println(permutation.toUpperCase());
}
}
private static List<Integer> findVarPositions(String input) {
List<Integer> varPositions = new ArrayList<>();
int lastVarPosition = -1;
while ((lastVarPosition = input.indexOf('0', lastVarPosition + 1)) != -1) {
varPositions.add(lastVarPosition);
}
return varPositions;
}
private static List<String> permutateAtPosition(List<String> partialyPermutated, int position) {
List<String> result = new ArrayList<>();
char[] replacements = {'1', '2', '3', '4', '5'};
for (String item : partialyPermutated) {
for (int i = 0; i < replacements.length; i++) {
String output = replaceCharAt(item, position, replacements[i]);
result.add(output);
}
}
return result;
}
private static String replaceCharAt(String input, int position, char replacement) {
//converting to char array, because there's no method like
//String.replaceAtPosition(position, char)
char[] charArray = input.toCharArray();
charArray[position] = replacement;
return new String(charArray);
}
}
It's not fixed to a number of variables.
The idea is to extract positions of '0' and subsequently call the method permutateAtPosition, which takes a partially permutated list and permutates it by one more level.
For "a0b0c0" and values 1-2 it would be ['a0b0c0'], then ['a1b0c0','a2b0c0'], then ['a1b1c0','a1b2c0','a2b1c0','a2b2c0'], and finally ['a1b1c1','a1b1c2','a1b2c1','a1b2c2','a2b1c1','a2b1c2','a2b2c1''a2b2c2'].
This solution keeps everything in memory, so in the general case (unlimited input string) it would be wiser to go with depth-first instead.
I've got another solution for you.
First step, getting the amount of variables:
int variableCount = 0;
for (int i = 0; i < 5; i++) {
if (input.charAt(i) == '0') {
variableCount++;
}
}
Then calculating the amount of results we are expecting:
int countMax = (int)Math.pow(4,variableCount);
Lastly, count up in base 4. Pad the number with 0's and replace the original input 0's:
for (int i = 0; i < countMax; i++) {
String paddedNumbers = format("%" + variableCount + "s",Integer.toString(i, 4)).replace(" ", "0");
int replacedCount = 0;
char[] outputChars = input.toCharArray();
for (int j = 0; j < 5; j++) {
if (input.charAt(j) == '0') {
outputChars[j] = paddedNumbers.charAt(replacedCount);
replacedCount++;
}
}
System.out.println(outputChars);
}
When converting an integer to int array, for example 123 to {1,2,3}, I am getting values {49,50,51}.
Not able to find what is wrong with my code.
public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = temp.charAt(i);
}
for (int i : newGuess) {
System.out.println(i);
}
}
}
Output:
49
50
51
charAt(i) will give you UTF-16 code unit value of the integer for example in your case, UTF-16 code unit value of 1 is 49.
To get integer representation of the value, you can subtract '0'(UTF-16 code unit value 48) from i.
public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = temp.charAt(i);
}
for (int i : newGuess) {
System.out.println(i - '0');
}
}
}
Output:
1
2
3
To add a little Java 8 niceties to the mix which allows us to pack everything up neatly, you can optionally do:
int i = 123;
int[] nums = Arrays.stream(String.valueOf(i).split(""))
.mapToInt(Integer::parseInt)
.toArray();
Here we get a stream to an array of strings created by splitting the string value of the given integer's numbers. We then map those into integer values with Integer#parseInt into an IntStream and then finally make that into an array.
temp.charAt(i) is basically returning you characters. You need to extract the Integer value out of it.
You can use:
newGuess[i] = Character.getNumericValue(temp.charAt(i));
Output
1
2
3
Code
public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = Character.getNumericValue(temp.charAt(i));
}
for (int i : newGuess) {
System.out.println(i);
}
}
}
As your interest is to get as an integer value of an string. Use the method parse int Integer.parseInt() . this will return as integer.
Example :
int x =Integer.parseInt("6"); It will return integer 6.
I am trying to convert decimal to binary numbers from the user's input using Java but so far, I'm running into errors I'm not sure why. What am I doing wrong? Don't mind the naming, ultimately I would like to convert decimal into binary without using if and while statements. Also without using the decimaltobinary string.
Thanks a lot.
package r
public static void main(String[] args) {
int number;
int remainder;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number=in.nextInt();
remainder= number %2;
System.out.print(remainder);
{
return null;
This is what I have so far.
This is how to convert a decimal to binary :
Using for loop :
public class DecimalToBinary {
public void printBinaryFormat(int decimalNumber){
int remainder = 0;
for (int i = 1; decimalNumber > 0; i++) {
remainder = decimalNumber % 2;
decimalNumber /= 2;
System.out.print(remainder);
}
}
public static void main(String a[]){
DecimalToBinary dtb = new DecimalToBinary();
dtb.printBinaryFormat(25);
}
}
Using while loop :
public class DecimalToBinary
{
public void printBinaryFormat(int number){
int binary[] = new int[25];
int index = 0;
while(number > 0){
binary[index++] = number%2;
number = number/2;
}
for(int i = index-1;i >= 0;i--){
System.out.print(binary[i]);
}
}
public static void main(String a[]){
DecimalToBinary dtb = new DecimalToBinary();
dtb.printBinaryFormat(25);
}
}
Hope I helped .
Happy Coding :D
Try this:
String binaryString = Long.toBinaryString(Double.doubleToRawLongBits(yourDecimalNumber));
Where yourDecimalNumber is the name of the decimal variable that you want to convert to binary.
You can also use a for loop and bitwise operation without using any if or while statements like so:
int number = 10;
String binaryString = "";
final int intBitSize = 32; // 32 is the number of bits in an int.
for(int i=0; i<intBitSize; i++)
{
binaryString = String.valueOf(number&1) + binaryString;
number = number >>> 1;
}
System.out.println(binaryString);
I have this input like
String s = "6" , ss="99 , sss = "99999";
i need to store these values in an int reference variable ,
without using Integer.parseInt
any suggestion ? , no full code , just the hints ??
What about Scanner?
int a=new Scanner(s).nextInt();
Without util.
public static int parseInt(String s)
{
int ans=0;
for(int i=s.length()-1;i>=0;i--)
{
ans+=(s.charAt(i)-'0');
ans*=10;
}
return ans/10;
}
public class MyStringToNumber {
public static int convert_String_To_Number(String numStr){
char ch[] = numStr.toCharArray();
int sum = 0;
//get ascii value for zero
int zeroAscii = (int)'0';
for(char c:ch){
int tmpAscii = (int)c;
sum = (sum*10)+(tmpAscii-zeroAscii);
}
return sum;
}
public static void main(String a[]){
System.out.println("\"3256\" == "+convert_String_To_Number("3256"));
System.out.println("\"76289\" == "+convert_String_To_Number("76289"));
System.out.println("\"90087\" == "+convert_String_To_Number("90087"));
}
}
See more at this URL.
Try to get each char from the string and then the value of each char. 0 has a value of 48 so
char c = '9';
int i = c - 48;
Now i = 9. After that you only need to multiply this value with the appropriate power of 10 and add it to the total
public class ConvertIntoInt {
public static void main(String []args) {
String numStr = "3256";
char ch[] = numStr.toCharArray();
int sum = 0;
// Get ASCII value for zero
int zeroAscii = (int)'0';
for (char c:ch) {
int tmpAscii = (int)c;
System.out.println("Temp Ascii:" + tmpAscii);
sum = (sum * 10) + (tmpAscii - zeroAscii);
System.out.println(sum);
}
System.out.println(sum);
}
}
I'm trying to solve the string similarity question on interviewstreet.com. My code is working for 7/10 cases (and it is exceeding the time limit for the other 3).
Here's my code -
public class Solution {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String v1 = user_input.next();
int number_cases = Integer.parseInt(v1);
String[] cases = new String[number_cases];
for(int i=0;i<number_cases;i++)
cases[i] = user_input.next();
for(int k=0;k<number_cases;k++){
int similarity = solve(cases[k]);
System.out.println(similarity);
}
}
static int solve(String sample){
int len=sample.length();
int sim=0;
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
if(sample.charAt(j-i)==sample.charAt(j))
sim++;
else
break;
}
}
return sim;
}
}
Here's the question -
For two strings A and B, we define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings "abc" and "abd" is 2, while the similarity of strings "aaa" and "aaab" is 3.
Calculate the sum of similarities of a string S with each of it's suffixes.
Input:
The first line contains the number of test cases T. Each of the next T lines contains a string each.
Output:
Output T lines containing the answer for the corresponding test case.
Constraints:
1 <= T <= 10
The length of each string is at most 100000 and contains only lower case characters.
Sample Input:
2
ababaa
aa
Sample Output:
11
3
Explanation:
For the first case, the suffixes of the string are "ababaa", "babaa", "abaa", "baa", "aa" and "a". The similarities of each of these strings with the string "ababaa" are 6,0,3,0,1,1 respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11.
For the second case, the answer is 2 + 1 = 3.
How can I improve the running speed of the code. It becomes harder since the website does not provide a list of test cases it uses.
I used char[] instead of strings. It reduced the running time from 5.3 seconds to 4.7 seconds and for the test cases and it worked. Here's the code -
static int solve(String sample){
int len=sample.length();
char[] letters = sample.toCharArray();
int sim=0;
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
if(letters[j-i]==letters[j])
sim++;
else
break;
}
}
return sim;
}
used a different algorithm. run a loop for n times where n is equals to length the main string. for each loop generate all the suffix of the string starting for ith string and match it with the second string. when you find unmatched character break the loop add j's value to counter integer c.
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Solution {
public static void main(String args[]) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(in.readLine());
for (int i = 0; i < T; i++) {
String line = in.readLine();
System.out.println(count(line));
}
}
private static int count(String input) {
int c = 0, j;
char[] array = input.toCharArray();
int n = array.length;
for (int i = 0; i < n; i++) {
for (j = 0; j < n - i && i + j < n; j++)
if (array[i + j] != array[j])
break;
c+=j;
}
return c;
}
}
I spent some time to resolve this question, and here is an example of my code (it works for me, and pass thru all the test-cases):
static long stringSimilarity(String a) {
int len=a.length();
char[] letters = a.toCharArray();
char localChar = letters[0];
long sim=0;
int sameCharsRow = 0;
boolean isFirstTime = true;
for(int i=0;i<len;i++){
if (localChar == letters[i]) {
for(int j = i + sameCharsRow;j<len;j++){
if (isFirstTime && letters[j] == localChar) {
sameCharsRow++;
} else {
isFirstTime = false;
}
if(letters[j-i]==letters[j])
sim++;
else
break;
}
if (sameCharsRow > 0) {
sameCharsRow--;
sim += sameCharsRow;
}
isFirstTime = true;
}
}
return sim;
}
The point is that we need to speed up strings with the same content, and then we will have better performance with test cases 10 and 11.
Initialize sim with the length of the sample string and start the outer loop with 1 because we now in advance that the comparison of the sample string with itself will add its own length value to the result.
import java.util.Scanner;
public class StringSimilarity
{
public static void main(String args[])
{
Scanner user_input = new Scanner(System.in);
int count = Integer.parseInt(user_input.next());
char[] nextLine = user_input.next().toCharArray();
try
{
while(nextLine!= null )
{
int length = nextLine.length;
int suffixCount =length;
for(int i=1;i<length;i++)
{
int j =0;
int k=i;
for(;k<length && nextLine[k++] == nextLine[j++]; suffixCount++);
}
System.out.println(suffixCount);
if(--count < 0)
{
System.exit(0);
}
nextLine = user_input.next().toCharArray();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}