45

最近、就職の面接でプログラミングのパズルを解くように頼まれました。Excel の列の文字を実際の数字に変換することについてです。思い出すと、Excel はその列に A から Z までの文字で名前を付け、そのシーケンスは AA、AB、AC... AZ、BA、BB などになります。

文字列をパラメーターとして受け入れ(「AABCCE」など)、実際の列番号を返す関数を作成する必要があります。

ソリューションはどの言語でもかまいません。

4

28 に答える 28

36

私には標準的な削減のように聞こえます:

パイソン:

def excel2num(x): 
    return reduce(lambda s,a:s*26+ord(a)-ord('A')+1, x, 0)

C#:

int ExcelToNumber(string x) {
    return x.Aggregate(0, (s, c) => s * 26 + c - 'A' + 1 );
}
于 2009-06-17T01:04:12.870 に答える
16

私はこれをPythonスクリプトのために何年も前に書きました:

def index_to_int(index):
    s = 0
    pow = 1
    for letter in index[::-1]:
        d = int(letter,36) - 9
        s += pow * d
        pow *= 26
    # excel starts column numeration from 1
    return s
于 2009-04-18T17:07:25.037 に答える
6

STDIN から列名を読み取り、対応する番号を出力します。

perl -le '$x = $x * 26 - 64 + ord for <> =~ /./g; print $x'

警告: ASCII を想定しています。

編集:"シェルが文字列を補間し'ないように置き換え$xます。

于 2009-04-18T16:59:57.147 に答える
4

はぁ - 私たちのコードベースにすでに書いています - 約3回:(

%% @doc Convert an string to a decimal integer
%% @spec b26_to_i(string()) -> integer()

b26_to_i(List) when is_list(List) ->
    b26_to_i(string:to_lower(lists:reverse(List)),0,0).

%% private functions
b26_to_i([], _Power, Value) -> 
    Value;

b26_to_i([H|T],Power,Value)->
    NewValue = case (H > 96) andalso (H < 123) of
                   true ->
                       round((H - 96) * math:pow(26, Power));
                   _    ->
                       exit([H | T] ++ " is not a valid base 26 number")
               end,
    b26_to_i(T, Power + 1, NewValue + Value).

なぞなぞは、実際には数値の Base26 表現ではないということです (ここでは関数名に嘘をついています)。数値には 0 が含まれていないからです。

シーケンスは次のとおりです: A、B、C ... Z、AA、AB、AC

およびない: A、B、C ...Z、BA、BB、BC

(言語は Erlang, mais oui です)。

于 2009-04-18T16:22:44.303 に答える
4

次のように C でこれを行うことができます。

unsigned int coltonum(char * string)
{
   unsigned result = 0;
   char ch;

   while(ch = *string++)
      result = result * 26 + ch - 'A' + 1;

  return result;
}

エラー チェックは行われません。大文字の文字列に対してのみ機能します。文字列は null で終了する必要があります。

于 2009-06-17T01:18:44.587 に答える
1

名前から列番号を取得します

Java:

public int getColNum (String colName) {

    //remove any whitespace
    colName = colName.trim();

    StringBuffer buff = new StringBuffer(colName);

    //string to lower case, reverse then place in char array
    char chars[] = buff.reverse().toString().toLowerCase().toCharArray();

    int retVal=0, multiplier=0;

    for(int i = 0; i < chars.length;i++){
        //retrieve ascii value of character, subtract 96 so number corresponds to place in alphabet. ascii 'a' = 97 
        multiplier = (int)chars[i]-96;
        //mult the number by 26^(position in array)
        retVal += multiplier * Math.pow(26, i);
    }
    return retVal;
}
于 2010-01-07T16:56:26.890 に答える
1

別の Java:

public static int convertNameToIndex(String columnName) {
    int index = 0;
    char[] name = columnName.toUpperCase().toCharArray();

    for(int i = 0; i < name.length; i++) {
        index *= 26;
        index += name[i] - 'A' + 1;
    }

    return index;
}
于 2012-11-06T13:37:33.567 に答える
1

列A = 1と仮定

int GetColumnNumber(string columnName)
{
  int sum = 0;
  int exponent = 0;
  for(int i = columnName.Length - 1; i>=0; i--)
  {
    sum += (columnName[i] - 'A' + 1) *  (GetPower(26, exponent));
    exponent++;
  }
  return sum;
}

int GetPower(int number, int exponent)
{
  int power = 1;
  for(int i=0; i<exponent; i++)
    power *= number;
  return power;
}
于 2009-04-18T16:28:48.780 に答える
1

警告: これらのバージョンはどちらも、大文字の A から Z のみを想定しています。それらを改善するために、エラーチェックや大文字化を少し追加することは難しくありません。

スカラ

def excel2Number(excel : String) : Int = 
  (0 /: excel) ((accum, ch) => accum * 26 + ch - 'A' + 1)

ハスケル

excel2Number :: String -> Int
excel2Number = flip foldl 0 $ \accum ch -> accum * 26 + fromEnum ch - fromEnum 'A' + 1
于 2009-06-16T23:47:04.523 に答える
1

Java で int から列名を取得します (詳細はこちらを参照):

public String getColName (int colNum) {

   String res = "";

   int quot = colNum;
   int rem;        
    /*1. Subtract one from number.
    *2. Save the mod 26 value.
   *3. Divide the number by 26, save result.
   *4. Convert the remainder to a letter.
   *5. Repeat until the number is zero.
   *6. Return that bitch...
   */
    while(quot > 0)
    {
        quot = quot - 1;
        rem = quot % 26;
        quot = quot / 26;

        //cast to a char and add to the beginning of the string
        //add 97 to convert to the correct ascii number
        res = (char)(rem+97) + res;            
    }   
    return res;
}
于 2010-02-26T09:56:26.027 に答える
1

別の Delphi のもの:

function ExcelColumnNumberToLetter(col: Integer): string;
begin
  if (col <= 26) then begin
    Result := Chr(col + 64);
  end
  else begin
    col := col-1;
    Result := ExcelColumnNumberToLetter(col div 26) + ExcelColumnNumberToLetter((col mod 26) + 1);
  end;
end;
于 2011-08-11T11:32:06.987 に答える
1

簡単な Java ソリューション -->

public class ColumnName {

public static int colIndex(String col)
{   int index=0;
    int mul=0;
    for(int i=col.length()-1;i>=0;i--)
    {   
        index  += (col.charAt(i)-64) * Math.pow(26, mul);
        mul++;
    }
    return index;
}

public static void main(String[] args) {

    System.out.println(colIndex("AAA"));

}
于 2016-02-08T03:53:28.850 に答える
0

ここにCFMLがあります:

<cffunction name="ColToNum" returntype="Numeric">
    <cfargument name="Input" type="String" />
    <cfset var Total = 0 />
    <cfset var Pos = 0 />

    <cfloop index="Pos" from="1" to="#Len(Arguments.Input)#">
        <cfset Total += 26^(Pos-1) * ( Asc( UCase( Mid(Arguments.Input,Pos,1) ) ) - 64 ) />
    </cfloop>

    <cfreturn Total />
</cffunction>

<cfoutput>
    #ColToNum('AABCCE')#
</cfoutput>


気分が変なので、CFScript のバージョンを次に示します。

function ColToNum ( Input )
{
    var Total = 0;

    for ( var Pos = 1 ; Pos <= Len(Arguments.Input) ; Pos++ )
    {
        Total += 26^(Pos-1) * ( Asc( UCase( Mid(Arguments.Input,Pos,1) ) ) - 64 );
    }

    return Total;
}

WriteOutput( ColToNum('AABCCE') );
于 2009-04-18T16:39:01.783 に答える
0

… PHPのソリューションが必要でした。これは私が思いついたものです:

/**
 * Calculates the column number for a given column name.
 *
 * @param string $columnName the column name: "A", "B", …, "Y", "Z", "AA", "AB" … "AZ", "BA", … "ZZ", "AAA", …
 *
 * @return int the column number for the given column name: 1 for "A", 2 for "B", …, 25 for "Y", 26 for "Z", 27 for "AA", … 52 for "AZ", 53 for "BA", … 703 for "AAA", …
 */
function getColumnNumber($columnName){
    //  the function's result
    $columnNumber = 0;

    //  at first we need to lower-case the string because we calculate with the ASCII value of (lower-case) "a"
    $columnName = strtolower($columnName);
    //  ASCII value of letter "a"
    $aAsciiValue = ord('a') - 1;

    //  iterate all characters by splitting the column name
    foreach (str_split($columnName) as $character) {
        //  determine ASCII value of current character and substract with that one from letter "a"
        $characterNumberValue = ord($character) - $aAsciiValue;

        //  through iteration and multiplying we finally get the previous letters' values on base 26
        //  then we just add the current character's number value
        $columnNumber = $columnNumber * 26 + $characterNumberValue;
    }

    //  return the result
    return $columnNumber;
}

もちろん、foreach ループ内で一部を 1 行のコードにまとめるだけで、スクリプトを少し短縮できます。

//  …
$columnNumber = $columnNumber * 26 + ord($character) - ord('a') + 1;
//  …
于 2014-11-07T16:52:29.850 に答える
0

Python でのこのコードの別のバージョンを次に示します。

keycode=1
for i in range (1,len(word)):
    numtest[i]=word[i-1]
    keycode = keycode*26*int(wordtest[numtest[i]])
last=word[-1:]
keycode=keycode+int(wordtest[last])
print(keycode)
print(bin(keycode))
#Numtest and wordtest are dictionaries.
于 2015-10-16T21:51:16.047 に答える
0

文字列を、A、B、... Z で表される数字を基数 26 で表した列番号の反転と考えると役立ちますか?

于 2009-04-18T16:16:04.630 に答える
0

これは基本的に 26 進数の数字ですが、数字は 0 ~ 9 を使用せず、次に文字を使用せず、文字のみを使用するという違いがあります。

于 2009-04-18T16:18:17.870 に答える
0

少し関連していますが、より良い課題は逆です。列番号が与えられた場合、列ラベルを文字列として見つけます。

KOffice用に実装したQtバージョン:

QString columnLabel( unsigned column )
{
  QString str;
  unsigned digits = 1;
  unsigned offset = 0;

  column--;
  for( unsigned limit = 26; column >= limit+offset; limit *= 26, digits++ )
    offset += limit;

  for( unsigned c = column - offset; digits; --digits, c/=26 )
    str.prepend( QChar( 'A' + (c%26) ) );

  return str;
}
于 2009-04-18T22:48:20.117 に答える
0
def ExcelColumnToNumber(ColumnName):
    ColNum = 0
    for i in range(0, len(ColumnName)):
        # Easier once formula determined: 'PositionValue * Base^Position'
        # i.e. AA=(1*26^1)+(1*26^0)   or  792=(7*10^2)+(9*10^1)+(2*10^0)
        ColNum += (int(ColumnName[i],36) -9) * (pow(26, len(ColumnName)-i-1))
    return ColNum

ps 初めての Python スクリプトです。

于 2009-04-20T21:19:56.600 に答える
0

デルファイ:

// convert EXcel column name to column number 1..256
// case-sensitive; returns 0 for illegal column name
function cmColmAlfaToNumb( const qSRC : string ) : integer;
var II : integer;
begin
   result := 0;
   for II := 1 to length(qSRC) do begin
      if (qSRC[II]<'A')or(qSRC[II]>'Z') then begin
         result := 0;
         exit;
      end;
      result := result*26+ord(qSRC[II])-ord('A')+1;
   end;
   if result>256 then result := 0;
end;

-アル。

于 2009-04-19T23:25:15.870 に答える
0

Python では、reduce なし:

def transform(column_string):
    return sum((ascii_uppercase.index(letter)+1) * 26**position for position, letter in enumerate(column_string[::-1]))
于 2015-07-14T14:16:50.087 に答える
0

ウィキペディアには適切な説明とアルゴリズムがあります

http://en.wikipedia.org/wiki/Hexavigesimal

public static String toBase26(int value){
    // Note: This is a slightly modified version of the Alphabet-only conversion algorithm

    value = Math.abs(value);
    String converted = "";

    boolean iteration = false;

    // Repeatedly divide the number by 26 and convert the
    // remainder into the appropriate letter.
    do {
        int remainder = value % 26;

        // Compensate for the last letter of the series being corrected on 2 or more iterations.
        if (iteration && value < 25) {
            remainder--;
        }

        converted = (char)(remainder + 'A') + converted;
        value = (value - remainder) / 26;

        iteration = true;
    } while (value > 0);

    return converted;    
}
于 2013-01-23T16:38:49.527 に答える
0

Mr. Wizard の素晴らしい Mathematica コードを使用し、不可解な純粋関数を取り除きました!

columnNumber[name_String] := FromDigits[ToCharacterCode[name] - 64, 26]
于 2011-06-18T03:02:44.740 に答える
0

一般的な Lisp:

(defun excel->number (string)
  "Converts an Excel column name to a column number."
  (reduce (lambda (a b) (+ (* a 26) b))
          string
          :key (lambda (x) (- (char-int x) 64))))

編集:逆の操作:

(defun number->excel (number &optional acc)
  "Converts a column number to Excel column name."
  (if (zerop number)
      (concatenate 'string acc)
      (multiple-value-bind (rest current) (floor number 26)
        (if (zerop current)
            (number->excel (- rest 1) (cons #\Z acc))
            (number->excel rest (cons (code-char (+ current 64)) acc))))))
于 2009-04-18T19:25:03.023 に答える
0

別の [より不可解な] erlang の例:

col2int(String) -> col2int(0,String).
col2int(X,[A|L]) when A >= 65, A =< 90 ->
col2int(26 * X + A - 65 + 1, L);
col2int(X,[]) -> X.

および逆関数:

int2col(Y) when Y > 0 -> int2col(Y,[]).
int2col(0,L) -> L;
int2col(Y,L) when Y rem 26 == 0 -> 
   int2col(Y div 26 - 1,[(26+65-1)|L]);
int2col(Y,L) ->
   P = Y rem 26,
   int2col((Y - P) div 26,[P + 65-1|L]).
于 2009-04-19T01:39:09.427 に答える
0

このバージョンは純粋に機能的であり、代替の「コード」シーケンスを許可します。たとえば、文字「A」から「C」のみを使用したい場合です。Scala では、dcsobral からの提案があります。

def columnNumber(name: String) = {
    val code = 'A' to 'Z'

    name.foldLeft(0) { (sum, letter) =>
        (sum * code.length) + (code.indexOf(letter) + 1)
    }
}
于 2009-06-17T00:00:37.490 に答える
0

Mathematica では:

FromDigits[ToCharacterCode@# - 64, 26] &
于 2011-05-17T07:46:07.837 に答える