fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /** Answer to Stackoverflow question:
  8.  * https://stackoverflow.com/questions/64685241/why-does-col-variable-return-a-wrong-value
  9.  */
  10. class Ideone
  11. {
  12.  
  13. public static long toColumnNumber(String columnLabel) {
  14. final int asciiOffset = (int) 'A' - 1; // 64 = 65 - 1, so that (int) 'B' - asciiOffset == 2
  15. long columnNumber = 0;
  16.  
  17. for (int backwardsIndex=0; backwardsIndex < columnLabel.length(); backwardsIndex++) {
  18. char letter = columnLabel.charAt(columnLabel.length() - backwardsIndex -1);
  19. int letterAsNumber = (int) letter - asciiOffset;
  20. columnNumber += Math.pow(26, backwardsIndex) * letterAsNumber;
  21. }
  22.  
  23. return columnNumber;
  24. }
  25.  
  26. public static void main (String[] args) throws java.lang.Exception
  27. {
  28. final String A = "A";
  29. System.out.println(A + " should be 1, is: " + toColumnNumber(A));
  30. final String AA = "AA";
  31. System.out.println(AA + " should be 27, is: " + toColumnNumber(AA));
  32. final String ZZ = "ZZ";
  33. System.out.println(ZZ + " should be 702, is: " + toColumnNumber(ZZ));
  34.  
  35.  
  36. assert toColumnNumber("AUHS") == 31999L;
  37. }
  38. }
Success #stdin #stdout 0.08s 33984KB
stdin
Standard input is empty
stdout
A should be 1, is: 1
AA should be 27, is: 27
ZZ should be 702, is: 702