Problem of the Day
A new programming or logic puzzle every Mon-Fri

Leading Digit

Write a function that takes a positive integer as input and returns the leading digit in its decimal representation. For example, the leading digit of 123456 is 1. Can you do this without any conversions/casts to a string?

Permalink: http://problemotd.com/problem/leading-digit/

Comments:

  • Akshay Bist - 9 years ago

    Assuming only positive integers will be passed

    def leadingDigit(num):
        while (num >= 10):
            num /= 10
        return num
    

    reply permalink

  • Tibor - 9 years ago

    Using logarithms instead of loops (Pascal)

    The floating point operations might eat your hamster below.

    function LeadingDigit(AValue: integer): integer;
    begin
      AValue := Abs(AValue);
      if AValue = 0 then Result := 0
      else begin
        Result := AValue div Round(Power(10, Floor(Log10(AValue))));
        if Result = 10 then Result := 1;
      end;
    end;
    

    reply permalink

  • Anonymous - 9 years ago

    #python 2.7
    import math
    
    x = int(raw_input("Enter an Integer> "))
    
    y = int(math.floor(x/math.pow(10, math.floor(math.log10(x)))))
    
    print y
    

    reply permalink

  • k4rtik - 9 years ago

    A tiny Python function, assuming correct inputs, almost too easy:

    def leading(N):
        while N/10 > 0:
            N = N/10
        return N
    

    reply permalink

Content curated by @MaxBurstein