2009-05-15 11 views
6

私は最近インタビューでこの質問をしました:ライブラリ関数を使用せずに文字列を整数に解析する方法は?

"どのようにライブラリの関数を使わずに、言語に関係なく、 '12345'という文字列を整数表現12345に解析できますか?

私は2つの答えを考えましたが、面接官は3番目にあると言いました。

解決策1: '1' => 1、 '2' => 2などをマッピングする辞書を保管しておきます。一度に1文字ずつ解析し、辞書に追加し、プレース値で乗算します。結果を合計します。

解決策2:文字列を一度に1文字ずつ解析し、各文字から '0'を引きます。これはあなたに '1' - '0' = 0x1、 '2' - '0' = 0x2などを与えます。再び、場所の値を掛けて結果を合計します。

誰でも第3の解決策が考えられますか?

ありがとうございました。

答えて

7

私は、これはインタビュアーが後だったものである期待:このメソッドは、あなたが概説された方法よりもはるかに少ない操作を使用しています

number = "12345" 
value = 0 
for digit in number:     //Read most significant digit first 
    value = value * 10 + valueOf(digit) 

。 (ダウン

http://www.programminginterview.com/content/strings

スクロール:

+0

解決策2(ちょうどValueOf()を使用していません) – tanascius

+0

質問に2番目の答えが記載されていませんか? – Naveen

+1

「valueOf」とは何ですか?ライブラリ関数ですか? –

0

すべての文字列を整数対応にマップするディクショナリを、ある制限まで保持しますか?上限が小さい場合はおそらくであることを除いて、多分意味をなさないでしょう。 2桁または3桁。

0

大量の文字列表を参照することで、バイナリ検索をいつでも試すことができます。

だれが効率について何も言わなかった... :-)

3

が10でアキュムレータを掛け、一桁を解析するための2つの方法のいずれかを使用し、oposite順に文字列を解析し、その後に数字を追加アキュムレータ。

この方法では、プレース値を計算する必要はありません。同じ結果を得るたびにアキュムレータに10を掛けます。

2

Arteliusの答えは、独立した非常に簡潔な言語ですが、説明と、より詳細な回答だけでなく、CとJava実装をお探しの方のために、このページをチェックアウトすることができますまたは検索)を「Practice Question:ASCIIエンコードされた文字列を整数に変換します。「

0
#include<stdio.h> 
#include<string.h> 
#include<stdlib.h> 

int nod(long); 
char * myitoa(long int n, char *s); 
void main() 
{ 

    long int n; 
    char *s; 
    printf("Enter n"); 
    scanf("%ld",&n); 
    s=myitoa(n,s); 
    puts(s); 
} 

int nod(long int n) 
{ 
    int m=0; 
    while(n>0) 
    { 
    n=n/10; 
    m++; 
    } 
    return m; 
} 

char * myitoa(long int n, char *s) 
{ 

    int d,i=0; 
    char cd; 
    s=(char*)malloc(nod(n)); 
    while(n>0) 
    { 
    d=n%10; 
    cd=48+d; 
    s[i++]=cd; 
    n=n/10; 
    } 
    s[i]='\0'; 
    strrev(s); 
    return s; 
} 
2

// Javaのバージョン

public static int convert(String s){ 
    if(s == null || s.length() == 0){ 
     throw new InvalidParameterException(); 
    } 

    int ret = 0; 

    boolean isNegtive = false; 

    for(int i=0;i<s.length();i++){ 
     char c = s.charAt(i); 

     if(i == 0 && (c == '-')){ 
      isNegtive = true; 
      continue; 
     } 

     if(c - '0' < 0 || c - '0' > 10){ 
      throw new InvalidParameterException(); 
     } 

     int tmp = c - '0'; 

     ret *= 10; 
     ret += tmp; 

    } 

    return isNegtive ? (ret - ret * 2) : ret; 



} 

//ユニットテスト

@Test 
public void testConvert() { 

    int v = StringToInt.convert("123"); 
    assertEquals(v, 123); 

    v = StringToInt.convert("-123"); 
    assertEquals(v, -123); 

    v = StringToInt.convert("0"); 
    assertEquals(v, 0); 


} 

@Test(expected=InvalidParameterException.class) 
public void testInvalidParameterException() { 
    StringToInt.convert("e123"); 
} 

@Rule 
public ExpectedException exception = ExpectedException.none(); 
@Test 
public void testInvalidParameterException2() { 

    exception.expect(InvalidParameterException.class); 
    StringToInt.convert("-123r"); 

}

0

これは、ライブラリを使用せずに、負、正のすべての条件を備えた完全なプログラムです

import java.util.Scanner; 


public class StringToInt { 
public static void main(String args[]) { 
    String inputString; 
    Scanner s = new Scanner(System.in); 
    inputString = s.nextLine(); 

    if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) { 
    System.out.println("error!!!"); 
    } else { 
    Double result2 = getNumber(inputString); 
    System.out.println("result = " + result2); 
    } 

} 
public static Double getNumber(String number) { 
    Double result = 0.0; 
    Double beforeDecimal = 0.0; 
    Double afterDecimal = 0.0; 
    Double afterDecimalCount = 0.0; 
    int signBit = 1; 
    boolean flag = false; 

    int count = number.length(); 
    if (number.charAt(0) == '-') { 
    signBit = -1; 
    flag = true; 
    } else if (number.charAt(0) == '+') { 
    flag = true; 
    } 
    for (int i = 0; i < count; i++) { 
    if (flag && i == 0) { 
    continue; 

    } 
    if (afterDecimalCount == 0.0) { 
    if (number.charAt(i) - '.' == 0) { 
    afterDecimalCount++; 
    } else { 
    beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0'); 
    } 

    } else { 
    afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0'); 
    afterDecimalCount = afterDecimalCount * 10; 
    } 
    } 
    if (afterDecimalCount != 0.0) { 
    afterDecimal = afterDecimal/afterDecimalCount; 
    result = beforeDecimal + afterDecimal; 
    } else { 
    result = beforeDecimal; 
    } 

    return result * signBit; 
} 
} 
関連する問題