import java.lang.Integer;
import java.util.Arrays;
public class Decimal {
//initialize intance variables
private int decimal;
private String hex;
public static void toHex(String s) {
int decimal = Integer.parseInt(s); //converts the s string into an int for binary conversion.
String hex = null;
int[] binNum = new int[16];
int[] binNumNibble = new int[4]; //A nibble is four bits.
int nibbleTot = 0;
char hexDig = '\0';
char[] cvtdHex = new char[4];
StringBuffer result = new StringBuffer();
for(int a = 32768; a == 1; a /= 2) { //32768 is the value of the largest bit.
int b = 0;//Will top at 15 at the end of the for loop. 15 references the last spot in the binNum array.
if(decimal > a) {
decimal -= a;
binNum[b++] = 1;//Arrays have a default value of zero to all elements. This provides a parsed binary number.
}
}
for(int a = 0; a == 15; a += 3) {
//Copies pieces of the binary number to the binNumNibble array. .arraycopy is used in java 1.5 and lower.
//Arrays.copyOfRange is used in java 1.5 and higher.
System.arraycopy(binNum, a, binNumNibble, 0, 4);
for(int b = 8; b == 1; a += 3) {
int c = 0;
nibbleTot += binNumNibble[c++];
//Converts the single hex value into a hex digit.
if(nibbleTot >= 1 && nibbleTot <= 9) {
hexDig += nibbleTot;
} else if(nibbleTot == 10) {
hexDig = 'A';
} else if(nibbleTot == 11) {
hexDig = 'B';
} else if(nibbleTot == 12) {
hexDig = 'C';
} else if(nibbleTot == 13) {
hexDig = 'D';
} else if(nibbleTot == 14) {
hexDig = 'E';
} else if(nibbleTot == 15) {
hexDig = 'F';
}
cvtdHex[c++] = hexDig;
}
}
//return hex = new String(cvtdHex);
hex = new String(cvtdHex);
System.out.print("Hex: " + hex);
}
}
I can't seem to figure out why variable hex is returned as a blank variable. I've been using System.out.print(); in each for loop and none of them are used, giving me the impression that the for loops are being skipped entirely, but I don't understand why and I'm on a time limit.
Any help is much appreciated, but please don't just paste code. I need to understand this for my computer science class!
yes, your for loops ARE being skipped, since the second part of the for statement is not the break condition but the condition that has to be fullfilled for the loop to run.
So it is NOT
for(a = 0; a == 15; a += 3)
but
for(a = 0; a <= 15; a += 3)
and so on...
The for loops wont execute because of the double ==
How about
String.format("%h", 256)
Related
I was given this problem in an interview, return the output of this String s = "4+8×2" , output = 20, Ex2: String s = "3×7-4", output = 17.
This is my approach, but I am not able to get the expected result, please point out the correct way here.
public static int findResult (String s) {
int i = 0;
Stack<String> stack = new Stack<>();
while (i < s.length()) {
if (s.charAt(i) == '+') {
stack.push(String.valueOf(s.charAt(i)));
i++;
} else if (s.charAt(i) == '*') {
stack.push(String.valueOf(s.charAt(i)));
i++;
} else if (s.charAt(i) == '-') {
stack.push(String.valueOf(s.charAt(i)));
i++;
} else if (Character.isDigit(s.charAt(i))) {
int num = s.charAt(i) - '0';
while (i+1 < s.length() && Character.isDigit(s.charAt(i + 1))) {
num = num * 10 + s.charAt(++i) - '0';
}
stack.push(String.valueOf(num));
i++;
}
}
int current = 0;
//second while loop
while (!stack.isEmpty()) {
int firstNumber = Integer.parseInt(stack.pop());
if (stack.isEmpty()) return current;
String sign = stack.pop(""
//int firstNum = Integer.parseInt(stack.pop());
if (sign.equals("*")) {
current = firstNumber * Integer.parseInt(stack.pop());
stack.push(String.valueOf(current));
}
else if (sign.equals("-")) {
current = firstNumber;
stack.push(String.valueOf(current));
} else {
current = firstNumber + Integer.parseInt(stack.pop());
stack.push(String.valueOf(current));
}
}
return Integer.parseInt(stack.pop());
}
This is how I approached this problem. (It is somewhat similar to yours). I'll post the code first, then explain the process below:
import java.util.*;
class Main {
public static void main(String[] args) {
System.out.println(findResult("2*57-38*3/5-5-2+3*4/2-2-2"));
}
public static double findResult (String s){
String sub = s;
ArrayList<Double> nums = new ArrayList<Double>();
ArrayList<Character> operations = new ArrayList<Character>();
for(int x = 0; x < s.length(); x++){
if(s.charAt(x) == '+' || s.charAt(x) == '-' || s.charAt(x) == '*' || s.charAt(x) == '/' ){
operations.add(s.charAt(x));
int subInd = sub.indexOf(s.charAt(x));
nums.add(Double.valueOf(sub.substring(0,subInd)));
sub = sub.substring(subInd + 1);
}
}
nums.add(Double.valueOf(sub));
String[] operationTypes = {"*/","+-"};
for(int i = 0; i < 2; i++){
for(int j = 0; j < operations.size(); j++){
if(operationTypes[i].indexOf(operations.get(j)) != -1){
double val;
if(operations.get(j) == '*'){
val = nums.get(j) * nums.get(j+1);
}
else if(operations.get(j) == '/'){
val = nums.get(j) / nums.get(j+1);
}
else if(operations.get(j) == '+'){
val = nums.get(j) + nums.get(j+1);
}
else{
val = nums.get(j) - nums.get(j+1);
}
nums.set(j,val);
nums.remove(j+1);
operations.remove(j);
j--;
}
}
}
return nums.get(0);
}
}
Yeah...it's a lot:
The first step in this process was to divide the String into two ArrayLists: nums and operations. nums stores the terms and operations stores the..operations (*, /, +, -).
Now, we iterate through each "group" of operations, that being multiplication and division, and addition and subtraction.
Starting with mult/div, if we see either a '*' or '/' in our operations, then we compute the product or quotient of the corresponding elements in our nums and edit nums accordingly by modifying the element that matches indexes with the operation and deleting the term following it. Make sure you also remove the operation from nums and decrement the counter variable so the loop does not skip any values.
Finally, we will return the only value left in our nums which will be our answer.
I hope this helped you! Please let me know if you need any further details or clarification :)
In my code, I want charSum to return 'X' if the remainder is 10 when the sum of 9 digits is divided by 9. I tried both charSum = 'X' and charSum = (char) 88 and neither works. Something in my algorithm must be wrong. Please help.
public static char getCheckSum(String isbn) {
int sum = 0;
for (int i = 0; i < isbn.length(); i++) {
int[] num = new int[isbn.length()];
num[i] = Character.getNumericValue(isbn.charAt(i));
sum = sum + num[i];
}
int last = (sum % 11);
char charSum;
if (last == 10){
charSum = 'X';
} else {
charSum = (char) (last + 48);
}
return charSum;
}
public static String formatISBNWithHyphens(String isbn) {
// original isbn: 123456789
// possible new isbn: 1-234-56789-X
char isbn10 = getCheckSum(isbn);
String isbn10Str = isbn + Character.toString(isbn10);
// char[] c = new char[isbn10Str.length()]; *leaving this here for future learning.
String[] cStr = new String[isbn10Str.length()];
String isbnStr = "";
for (int i = 0; i < isbn10Str.length(); i++){
cStr[i] = Character.toString(isbn10Str.charAt(i));
// c[i] = isbn10Str.charAt(i); *leaving this here for future learning.
if (i == 0 || i == 3 || i == 8 ) {
cStr[i] += '-';
}
isbnStr += cStr[i];
}
return isbnStr;
}
It works fine. If I run it with 933456789 (the sum of which is 54, so 54 % 11 = 10), the getCheckSum() method returns X as expected.
However, this does not seem like the correct way to calculate an ISBN-10 checksum. According to Wikipedia:
The 2001 edition of the official manual of the International ISBN
Agency says that the ISBN-10 check digit – which is the last digit of
the ten-digit ISBN – must range from 0 to 10 (the symbol X is used for
10), and must be such that the sum of all the ten digits, each
multiplied by its (integer) weight, descending from 10 to 1, is a
multiple of 11.
I've implemented it according to the specification as follows:
public static char getCheckDigit(String isbn) {
if (isbn == null || !isbn.matches("[0-9]{9,}")) {
throw new IllegalArgumentException("Illegal ISBN value");
}
int sum = 0;
for (int i = 0; i < 9; i++) {
sum += ((10 - i) * Character.digit(isbn.charAt(i), 10));
}
int check = ((11 - (sum % 11)) % 11);
return check == 10 ? 'X' : Character.forDigit(check, 10);
}
Applied to a couple of ISBN values I found on the same Wikipedia page:
getCheckDigit("097522980"); // --> returns 'X'
getCheckDigit("094339604"); // --> returns '2'
getCheckDigit("999215810"); // --> returns '7'
public class HelloWorld{
public static char getCheckSum(String isbn) {
int sum = 0;
for (int i = 0; i < isbn.length(); i++) {
int[] num = new int[isbn.length()];
num[i] = Character.getNumericValue(isbn.charAt(i));
System.out.println(num[i]);
sum = sum + num[i];
System.out.println(sum);
}
int last = (sum % 11);
char charSum;
if (last == 10){
charSum = 'X';
} else {
charSum = (char) (last + 48);
}
return charSum;
}
public static void main(String []args){
String isbn="123456787";
// possible new isbn: 1-234-56789-X
char isbn10 = getCheckSum(isbn);
System.out.println(isbn10);
}
}
it's working fine :)
I am writing my own big integer class in java without imports and need a method for doubling a number of any size that is represented by a string. The code I have for this now works, but begins to take a long time once the numbers get bigger and bigger. I essentially create two arrays: the main array and the countdown array which both start as the same thing. Then, I run a while loop and increment the main array up and increment the countdown array down. When the countdown array reaches "0", I terminate the loop and the result is a new array with the new number doubled in size. Then of course I have if statements checking whether the arrays need to change the ten's place, etc.... here's what I have... Is there any way I can make it more efficient and quick?
public static String doubleDecimalString (String main) {
String countdown = main;
String finalBuild = "";
boolean runLoop = true;
//if zero is supplied, skip all the nonsense and just return 0
//else, loop through and find the true double
//was having trobule getting single digits to double correctly so i had to hard code this for now.
if (main.equals("0")) {
return main;
} else if (main.equals("5")) {
return "10";
} else if (main.equals("6")) {
return "12";
} else if (main.equals("7")) {
return "14";
} else if (main.equals("8")) {
return "16";
} else if (main.equals("9")) {
return "18";
} else {
//Array for ORIGINAL NUMBER
int[] mainPiece = new int[main.length()+2];
int arrayLength = mainPiece.length;
for ( int i = 0; i < main.length(); i++ ) {
mainPiece[i+2] = Integer.parseInt(main.substring( i, i+1));
}
mainPiece[0] = -1;
mainPiece[1] = -1;
//Array for COUNTDOWN NUMBER
int[] countdownPiece = new int[main.length()+2];
for ( int i = 0; i < main.length(); i++ ) {
countdownPiece[i+2] = Integer.parseInt(main.substring( i, i+1));
}
countdownPiece[0] = -1;
countdownPiece[1] = -1;
while ( runLoop ) {
//Increment and decrement the two arrays
mainPiece[arrayLength-1] += 1;
countdownPiece[arrayLength-1] -= 1;
//UPDATE MAIN ARRAY
if ( mainPiece[arrayLength-1] == 10 ) {
for (int x = arrayLength-1; x > 0; x--) {
if ( (mainPiece[x] == 10) && (mainPiece[x-1] != 9) ) {
mainPiece[x] = 0;
mainPiece[x -1] += 1;
} else if ( (mainPiece[x] == 10) && (mainPiece[x-1] == 9) ) {
mainPiece[x] = 0;
mainPiece[x -1] += 1;
x = arrayLength;
}
if ( (mainPiece[2] == 10) ) {
mainPiece[1] = 1;
mainPiece[2] = 0;
}
}
} // end main array
//UPDATE SIDE ARRAY
if ( countdownPiece[arrayLength-1] == -1 ) {
for (int x = arrayLength-1; x > 0; x--) {
if ( (countdownPiece[x] == -1) && (countdownPiece[x-1] > 0) && (x > 1) ) {
countdownPiece[x] = 9;
countdownPiece[x -1] -= 1;
} else if ( (countdownPiece[x] == -1) && (countdownPiece[x-1] == 0) && (x > 1) ) {
countdownPiece[x] = 9;
countdownPiece[x -1] -= 1;
x = arrayLength;
}
}
} //end side array
//tests whether the pieces need to be switched to -1 for scanning
for (int x = 0; x < arrayLength - 1; x++) {
if ( (countdownPiece[x] == -1 ) && (countdownPiece[x+1] == 0 ) ) {
countdownPiece[x+1] = -1;
}
}
//if the side array has reached "0" then the loop will stop and the main array will return the new doubled value
if ( (countdownPiece[arrayLength-1] == -1) && (countdownPiece[arrayLength-2] == -1) ) {
break;
}
} //end while loop
//transform array into string
finalBuild = "";
for (int T = 0; T < arrayLength; T++) {
finalBuild += (mainPiece[T] != -1) ? mainPiece[T] : "";
}
return finalBuild;
}
}
How about something like this (it basically does a multiply by two and accounts for carries):
private String doubleNumber(String number)
{
int doubleDig = 0;
int carry = 0;
StringBuilder sb = new StringBuilder();
for (int i = number.length() - 1; i >= 0; --i)
{
char c = number.charAt(i);
int origNum = Character.getNumericValue(c);
doubleDig = origNum * 2 + carry;
carry = doubleDig / 10;
doubleDig = doubleDig % 10;
sb.append(doubleDig);
}
if (carry > 0)
{
sb.append(carry);
}
return sb.reverse().toString();
}
Obviously this only handles integers.
I would use StringBuilder or List to build your doubled value.
Use a carry variable to store the carry amount and initialize to 0.
Start at the least significant digit, double the digits and add the carry.
Then set the carry to digit / 10, then the digit to digit % 10
Append digit to your builder or list.
After you loop through all your digits, check if carry is > 0 and append if needed.
Reverse the StringBuilder or list and join and you have your answer.
public class Doubler {
public static void main(String[] args) {
System.out.println(doubleDec("9123123123087987342348798234298723948723987234982374928374239847239487.23233099"));
}
public static String doubleDec(String dec) {
StringBuilder builder = new StringBuilder();
int carry = 0;
for (int i = dec.length() - 1; i > -1 ; i--) {
char charDigit = dec.charAt(i);
if (charDigit == '.') {
builder.append(charDigit);
} else {
int digit = Character.getNumericValue(charDigit);
if (digit == -1) {
throw new IllegalStateException("Invalid character in decimal string.");
}
digit = digit * 2 + carry;
carry = digit / 10;
digit = digit % 10;
builder.append(digit);
}
}
if (carry != 0) {
builder.append(carry);
}
return builder.reverse().toString();
}
}
// 18246246246175974684697596468597447897447974469964749856748479694478974.46466198
I have an assignment to create my own implementation of a class to handle integers of unlimited size, and then to compare my implementation's runtime to that of Java's BigInteger. When I measured and graphed the runtime of my add function it was a parabola, implying a big theta running time of Ө(n^2). I have no nested loops so I expected it to be Ө(n) and cannot figure out why it isn't. I suspect it might be that I use
string += integer
in my add method inside a loop. I am not quite sure how that operation is implemented, is it a runtime of Ө(n)? If not, can anyone spot why my code isn't Ө(n)?
Here is my add method and the constructor it calls.
public HugeInteger(String val) throws IllegalArgumentException{
String temp = "";
boolean leading = true;
//check valid input
for(int i=0; i<val.length(); i++){
if(val.charAt(i) < '0' || val.charAt(i) > '9') //checks if each digit is a number from 0 to 9
if(i!=0 || val.charAt(i) != '-') //doesn't throw if the digit is a '-' at the first character of string
throw new IllegalArgumentException("Input string must be a number");
}
//remove leading zeros
for(int i=0; i<val.length(); i++){
if(!leading || val.charAt(i) != '0')
temp += val.charAt(i);
if(val.charAt(i) > '0' && val.charAt(i) <= '9') //reached first non-zero digit
leading = false;
}
if(temp == "") //this happens when the input was just a string of zeros
temp = "0";
val = temp;
if(val.charAt(0) != '-'){ //no negative sign
digits = new int[val.length()];
for(int i=0; i<val.length(); i++){
digits[i] = (int)(val.charAt(val.length()-1-i) - 48); //in ASCII the char '0' == 48
}
negative = false;
}
else{
digits = new int[val.length() - 1];
for(int i=1; i<val.length(); i++){ //for loop starts after the '-' sign
digits[i-1] = (int)(val.charAt(val.length()-i) - 48); //in ASCII the char '0' == 48
}
negative = true;
}
}
public HugeInteger add(HugeInteger h){
int carry = 0;
int size = digits.length>h.digits.length?digits.length:h.digits.length; //choose larger # of digits
String sum = "";
String sumFlipped = "";
int bigger = 0;
boolean swapped = false;
int temp;
int sign = 1;
int hsign = 1;
//assign sign based on negative or not
if(negative && !h.negative)
sign = -1;
if(!negative && h.negative)
hsign = -1;
//compare magnitudes. 1 means this is biger and -1 means h is bigger
if(digits.length>h.digits.length)
bigger = 1;
else if(digits.length<h.digits.length)
bigger = -1;
else{ //same length
for(int i=0; i<digits.length; i++){ //both digits arrays are same length
if(digits[digits.length-1-i] > h.digits[h.digits.length-1-i]){
bigger = 1;
break;
}
if(digits[digits.length-1-i] < h.digits[h.digits.length-1-i]){
bigger = -1;
break;
}
}
}
//positive number must be bigger than negative number for long subtraction
//if not, swap signs
if(bigger == 1 && negative && !h.negative){ //this is bigger and negative
swapped = true;
sign *= -1;
hsign *= -1;
}
if(bigger == -1 && !negative && h.negative){ //h is bigger and negative
swapped = true;
sign *= -1;
hsign *= -1;
}
for(int i=0; i<size; i++){
if(i>=digits.length)
temp = h.digits[i]*hsign + carry;
else if(i>=h.digits.length)
temp = digits[i]*sign + carry;
else
temp = digits[i]*sign + h.digits[i]*hsign + carry;
if(temp>9){ //adds the digit to the string, then increments carry which is used in next iteration
temp -= 10;
sum += temp;
carry = 1;
}
else if(temp<0){
temp += 10;
carry = -1;
sum += temp;
}
else{
sum += temp;
carry = 0;
}
}
if(carry == 1)
sum += 1;
if(negative && h.negative || swapped)
sum += '-';
//flip string around
for(int i=0; i < sum.length(); i++){
sumFlipped += sum.charAt(sum.length() - 1 - i);
}
HugeInteger sumHugeInteger = new HugeInteger(sumFlipped);
return sumHugeInteger;
}
It might be a weird question, but I havent found any binary division java implementation browsing the internet. I will use it for CRC16 coding, so converting to decimal is not a solution. I understand the method on paper, but I am a beginner and since it's very important I wouldn't want to make it wrong. The only thing I found is a CRC.java on the code.google.com which uses binary division, but even if I only use the division part of that (removing the other parts) I dont get the desirable value.
Anybody can show me a java implementation of it? I'd appreciate it very much! Thanks in advance
The code what I found:
public class CRC {
private String data, divisor;
public CRC(String d, String di) {
this.data = d;
this.divisor = di;
}
public String getRemainder(String data, String divisor) {
int x = 1, z = divisor.length(), j = 0, i;
String data2 = "", strOfZeros = "";
int y = divisor.length() - 1;
/* This is to get correct amount of zero's onto the end of the data */
while (y > 0) {
data += "0";
y--;
}
// Main part of method, this is the long division of Binary numbers.
needToExit: for (i = x, j = 1; i < z && z <= data.length(); i++, j++) {
if (z == data.length() && data2.charAt(0) == '1') {
strOfZeros = "";
for (i = 1; i < divisor.length(); i++) {
if (data2.charAt(i) == divisor.charAt(i))
strOfZeros += '0';
else
strOfZeros += '1';
}
data2 = strOfZeros;
break needToExit;
}
if (data.charAt(i) == divisor.charAt(j))
data2 += "0";
else
data2 += "1";
if (i == divisor.length() - 1) {
data2 += data.charAt(z);
x++;
z++;
// i = x;
j = 0;
// when first bit is a 0
while (data2.charAt(0) != '1' && i == divisor.length() - 1) {
for (i = 1; i < divisor.length(); i++) {
if (data2.charAt(i) == '0')
strOfZeros += "0";
else
strOfZeros += "1";
}
strOfZeros += data.charAt(z);
data2 = strOfZeros;
strOfZeros = "";
x++;
z++;
i = x;
}
}
}
return data2;
}
public String getDataPlusCRC(String data){
String str = data.concat(getRemainder(this.data, this.divisor));
return str;
}
}
The getRemainder() method gives me a bad result when I try to divide to numbers. And this part is not necessary, because it needs for the CRC.
while (y > 0) {
data += "0";
y--;
}
BigInteger can do base 2 division;
BigInteger divisor = new BigInteger("10", 2);
BigInteger dividend = new BigInteger("100", 2);
BigInteger result = dividend.divide(divisor);
System.out.println(result.toString(2));