I can\'t figure out this method. Don\'t change the method type. Decoding UTF8. i
ID: 3728615 • Letter: I
Question
I can't figure out this method. Don't change the method type. Decoding UTF8.
import java.util.Scanner;
public class Battleship {
/**
* This method converts a String representing a base (or radix) 26 number into a decimal (or
* base 10) number. The String representation of the base 26 number uses the letters of the
* Latin alphabet to represent the 26 digits. That is, A represents 0, B represents 1, C
* represents 2, ..., Y represents 24, and Z represents 25.
*
* A couple of examples:
* BAAA = 1 * 26^3 + 0 * 26^2 + 0 * 26^1 + 0 * 26^0 = 17576
* ZERTY = 25 * 26^4 + 4 * 26^3 + 17 * 26^2 + 19 * 26^1 + 24 * 26^0 = 11506714
* "&é"" = -14747
* For this method:
* - use Math.pow to calculate the powers of 26.
* - don't assume that the input is in any particular case; use toUpperCase().
* - don't check that the input is only 'A' to 'Z'.
* - calculate the value of each digit relative to 'A'.
* - start from either the first or last character, and calculate the exponent based on the
* index of each character.
*
* @param coord The coordinate value in base 26 as described above.
* @return The numeric representation of the coordinate.
*/
public static int coordAlphaToNum(String coord) {
//FIXME
return -1;
}
public static void main(String[] args) {
//FIXME
}
}
Explanation / Answer
public class Battleship {
/**
* This method converts a String representing a base (or radix) 26 number into a decimal (or
* base 10) number. The String representation of the base 26 number uses the letters of the
* Latin alphabet to represent the 26 digits. That is, A represents 0, B represents 1, C
* represents 2, ..., Y represents 24, and Z represents 25.
*
* A couple of examples:
* BAAA = 1 * 26^3 + 0 * 26^2 + 0 * 26^1 + 0 * 26^0 = 17576
* ZERTY = 25 * 26^4 + 4 * 26^3 + 17 * 26^2 + 19 * 26^1 + 24 * 26^0 = 11506714
*
* For this method:
* - use Math.pow to calculate the powers of 26.
* - don't assume that the input is in any particular case; use toUpperCase().
* - don't check that the input is only 'A' to 'Z'.
* - calculate the value of each digit relative to 'A'.
* - start from either the first or last character, and calculate the exponent based on the
* index of each character.
*
* @param coord The coordinate value in base 26 as described above.
* @return The numeric representation of the coordinate.
*/
public static int coordAlphaToNum(String coord) {
//FIXME
int ans = 0;
for(int i=0; i<coord.length(); i++) {
int e = Character.toUpperCase(coord.charAt(i)) - 'A';
ans = ans + e*(int)Math.pow(26, coord.length()-i-1);
}
return ans;
}
public static void main(String[] args) {
System.out.println(coordAlphaToNum("BAAA"));
System.out.println(coordAlphaToNum("ZERTY"));
}
}
/*
Sample run:
17576
11506714
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.