Editorial
Algorithm Analysis
The last digit of the number equals .
We divide the number by 10 until it is greater than 9. Now will contain the first digit of the input number: .
Find and output the sum of the first and last digit.
Solution using a string. Read the number as a string s
. If the string starts with the ‘-‘ symbol (the input number is negative), then the first digit of the number is located in s[1]
. Find the last digit by calculating the length of the string.
Algorithm Implementation
Read the input number .
scanf("%d", &n);
If the number is negative, then change the sign of the number to the opposite.
if (n < 0) n = -n;
The last digit of the number equals .
last = n % 10;
Divide the number by 10 until it is greater than 9. Now contains the first digit of the input number.
while (n > 9) n = n / 10;
first = n;
Calculate and output the answer.
res = first + last; printf("%d\n", res);
String-based Algorithm Implementation
Read the input number into a string s
.
char s[100];
Read the input number. Set pos
equal to the index indicating the first digit of the number.
gets(s); pos = (s[0] == '-') ? 1 : 0;
Find the sum of the first s[pos]
– ‘0’ and the last s[strlen(s) – 1]
– ‘0’ digit.
sum = s[pos] + s[strlen(s)-1] - 2*'0';
Output the answer.
printf("%d\n",sum);
Java Implementation
import java.util.*; public class Main { public static void main(String[] args) { Scanner con = new Scanner(System.in); char[] s = con.nextLine().toCharArray(); int pos = 0; if (s[0] == '-') pos = 1; int res = s[pos] + s[s.length - 1] - 2 * '0'; System.out.println(res); con.close(); } }
Python Implementation
Read the input number .
n = int(input())
If the number is negative, then change the sign of the number to the opposite.
if n < 0: n = -n
Convert the number to a string.
n = str(n)
Output the sum of the first and last digit.
print(int(n[0]) + int(n[-1]))