문제

여기에는 코딩에 대한 문제는 이와 같은 종류의 것입니다.Let's 참조 구현(에서 언어의 선택,of course)의 기능을 반환하는 사람이 읽을 수 있는 문자열 표현은 지정된 정수입니다.예를 들어:

  • humanReadable(1)반환합니다"하나".
  • humanReadable(53)는"쉰".
  • humanReadable(723603)반환합니다"일곱 hundred and twenty-three thousand,백 및 세".
  • humanReadable(1456376562)반환한"억백 fifty-six million,세 백 및 일흔 여섯 천 오백 sixty-two".

보너스 포인트 특히 똑똑한/우아한 솔루션!

그럼 보일 수 있는 무의미한 운동만 있는 번호의 실제 응용 프로그램을 위해 이런 종류의 알고리즘(록 지원하는 숫자만큼 높은 억 수 있습 잔:-)

도움이 되었습니까?

해결책

이미 질문에 대해 이:변환의 정수를 기록번호

대답은 C#지만,나는 당신이 그것을 알아낼 수 있습니다.

다른 팁

import math

def encodeOnesDigit(num):
   return ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'][num]

def encodeTensDigit(num):
   return ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'][num-2]

def encodeTeens(num):
   if num < 10:
      return encodeOnesDigit(num)
   else:
      return ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'][num-10]

def encodeTriplet(num):
   if num == 0: return ''
   str = ''
   if num >= 100:
      str = encodeOnesDigit(num / 100) + ' hundred'
   tens = num % 100
   if tens >= 20:
      if str != '': str += ' '
      str += encodeTensDigit(tens / 10)
      if tens % 10 > 0:
         str += '-' + encodeOnesDigit(tens % 10)
   elif tens != 0:
      if str != '': str += ' '
      str += encodeTeens(tens)
   return str

def zipNumbers(numList):
   if len(numList) == 1:
      return numList[0]
   strList = ['', ' thousand', ' million', ' billion'] # Add more as needed
   strList = strList[:len(numList)]
   strList.reverse()
   joinedList = zip(numList, strList)
   joinedList = [item for item in joinedList if item[0] != '']
   return ', '.join(''.join(item) for item in joinedList)

def humanReadable(num):
   if num == 0: return 'zero'
   negative = False
   if num < 0:
      num *= -1
      negative = True
   numString = str(num)
   tripletCount = int(math.ceil(len(numString) / 3.0))
   numString = numString.zfill(tripletCount * 3)
   tripletList = [int(numString[i*3:i*3+3]) for i in range(tripletCount)]
   readableList = [encodeTriplet(num) for num in tripletList]
   readableStr = zipNumbers(readableList)
   return 'negative ' + readableStr if negative else readableStr

까지 지원 999 만는데,부정 번호:

String humanReadable(int inputNumber) {
  if (inputNumber == -1) {
    return "";
  }
  int remainder;
  int quotient;
  quotient = inputNumber / 1000000;
  remainder = inputNumber % 1000000;
  if (quotient > 0) {
    return humanReadable(quotient) + " million, " + humanReadable(remainder);
  }
  quotient = inputNumber / 1000;
  remainder = inputNumber % 1000;
  if (quotient > 0) {
    return humanReadable(quotient) + " thousand, " + humanReadable(remainder);
  }
  quotient = inputNumber / 100;
  remainder = inputNumber % 100;
  if (quotient > 0) {
    return humanReadable(quotient) + " hundred, " + humanReadable(remainder);
  }
  quotient = inputNumber / 10;
  remainder = inputNumber % 10;
  if (remainder == 0) {
    //hackish way to flag the algorithm to not output something like "twenty zero"
    remainder = -1;
  }
  if (quotient == 1) {
    switch(inputNumber) {
    case 10:
      return "ten";
    case 11:
      return "eleven";
    case 12:
      return "twelve";
    case 13:
      return "thirteen";
    case 14:
      return "fourteen";
    case 15:
      return "fifteen";
    case 16:
      return "sixteen";
    case 17:
      return "seventeen";
    case 18:
      return "eighteen";
    case 19:
      return "nineteen";
    }
  }
  switch(quotient) {
  case 2:
    return "twenty " + humanReadable(remainder);
  case 3:
    return "thirty " + humanReadable(remainder);
  case 4:
    return "forty " + humanReadable(remainder);
  case 5:
    return "fifty " + humanReadable(remainder);
  case 6:
    return "sixty " + humanReadable(remainder);
  case 7:
    return "seventy " + humanReadable(remainder);
  case 8:
    return "eighty " + humanReadable(remainder);
  case 9:
    return "ninety " + humanReadable(remainder);
  }
  switch(inputNumber) {
  case 0:
    return "zero";
  case 1:
    return "one";
  case 2:
    return "two";
  case 3:
    return "three";
  case 4:
    return "four";
  case 5:
    return "five";
  case 6:
    return "six";
  case 7:
    return "seven";
  case 8:
    return "eight";
  case 9:
    return "nine";
  }
}
using System;

namespace HumanReadable
{
    public static class HumanReadableExt
    {
        private static readonly string[] _digits = {
                                                       "", "one", "two", "three", "four", "five",
                                                       "six", "seven", "eight", "nine", "eleven", "twelve",
                                                       "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
                                                       "eighteen", "nineteen"
                                                   };

        private static readonly string[] _teens = {
                                                      "", "", "twenty", "thirty", "forty", "fifty",
                                                      "sixty", "seventy", "eighty", "ninety"
                                                  };

        private static readonly string[] _illions = {
                                                        "", "thousand", "million", "billion", "trillion"
                                                    };

        private static string Seg(int number)
        {
            var work = string.Empty;

            if (number >= 100) 
                work += _digits[number / 100] + " hundred ";

            if ((number % 100) < 20)
                work += _digits[number % 100];
            else
                work += _teens[(number % 100) / 10] + "-" + _digits[number % 10];

            return work;
        }

        public static string HumanReadable(this int number)
        {
            if (number == 0)
                return "zero";
            var work = string.Empty;

            var parts = new string[_illions.Length];

            for (var ind = 0; ind < parts.Length; ind++)
                parts[ind] = Seg((int) (number % Math.Pow(1000, ind + 1) / Math.Pow(1000, ind)));

            for (var ind = 0; ind < parts.Length; ind++)
                if (!string.IsNullOrEmpty(parts[ind]))
                    work = parts[ind] + " " + _illions[ind] + ", " + work;

            work = work.TrimEnd(',', ' ');

            var lastSpace = work.LastIndexOf(' ');
            if (lastSpace >= 0)
                work = work.Substring(0, lastSpace) + " and" + work.Substring(lastSpace);

            return work;
        }
    }

    class Program
    {

        static void Main(string[] args)
        {
            Console.WriteLine(1.HumanReadable());
            Console.WriteLine(53.HumanReadable());
            Console.WriteLine(723603.HumanReadable());
            Console.WriteLine(1456376562.HumanReadable());
            Console.ReadLine();
        }
    }
}

거기에 하나의 거대한 문제에 대해 이 기능을 구현합니다.그것은 그것의 미래의 현지화.는 기능에 의해 작성,영어 원어민,대부분의 아마도 작동하지 않을 것 어떤 영어 이외의 언어로.그것은 거의 불가능하여 쓰는 일반적인 쉬운 지역화할 수 있는 기능에 대한 모든 인간의 언어를 세계에서,당신이하지 않는 진짜 필요 그것을 유지하는 일반적이다.실제로 현실 세계에서 당신은 필요하지 않으로 작동하는 거대한 정수,그래서 당신은 단지 계속 할 수 있는 모든 숫자에서(또는 그렇게 크지 않다)문자열을 배열입니다.

기로 합의 수 있다는 것의 실제 응용 프로그램.이와 같이 이미 다수의 실제 구현입니다.

그것은 부품의 bsdgames 기 때문이 꽤 많다.

> man number
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top