Second digit of the number#1605

Second digit of the number (Editorial)

If the input number is negative, compute its absolute value — this will not change the second digit. Then divide the number by until it is greater than . The last digit of the resulting number will be the second digit of the initial number.

Algorithm implementation

Read the input number . Since it is -bit number, use the long long type. If it is negative, then change its sign to the opposite.

scanf("%lld",&n);
if (n < 0) n = -n;

Divide the number by until it is greater than .

while (n > 99) n /= 10;

The last digit of the resulting number will be the second digit of the initial number. Print it.

res = n % 10;
printf("%lld\n",res);

Java implementation

import java.util.*;

public class Main
{
  public static void main(String []args)
  {
    Scanner con = new Scanner(System.in);
    long n = con.nextLong();
    if (n < 0) n = -n;

    while (n > 99) n /= 10;
    long res = n % 10;

    System.out.println(res);      
    con.close();
  }
} 

Python implementation — arithmetic approach

Read the input number .

n = int(input())

If the number is negative, then change its sign to the opposite.

if n < 0: n = -n

Divide the number by until it is greater than .

while n > 99:
  n = n // 10

The last digit of the resulting number will be the second digit of the initial number. Print it.

res = n % 10
print(res)

Python implementation — string

Read the input number .

n = int(input())

Compute the absolute value of the number . Then, convert it to a string, extract the first character (string indexing starts at zero), and convert it back to an integer.

res = int(str(abs(n))[1])

Print the answer.

print(res)