To solve the “Bit++” problem, you are given a sequence of operations that modify the value of a variable x
. Initially, x
is set to 0
, and you need to determine the final value of x
after executing all the given statements.
Key Observations:
- You are given
n
statements, where each statement is one of the following:"++X"
,"X++"
— both increment the value ofx
by 1."--X"
,"X--"
— both decrement the value ofx
by 1.
- Regardless of the position of the operator relative to
X
(++X
,X++
,--X
, orX--
), the operation performed onx
remains the same:++
increasesx
by 1.--
decreasesx
by 1.
Approach:
- Start with
x = 0
. - For each statement, check if it contains “++” or “–“.
- If it contains “++”, increment
x
. - If it contains “–“, decrement
x
.
- If it contains “++”, increment
- After processing all statements, output the final value of
x
.
Solution in__
Python:
n = int(input()) # Reading the number of statements
x = 0 # Initial value of x
for _ in range(n):
statement = input().strip()
if "++" in statement:
x += 1
elif "--" in statement:
x -= 1
print(x)
PythonC#:
using System;
class Program
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
int x = 0;
for (int i = 0; i < n; i++)
{
string statement = Console.ReadLine();
if (statement.Contains("++"))
{
x++;
}
else if (statement.Contains("--"))
{
x--;
}
}
Console.WriteLine(x);
}
}
C#Go:
package main
import (
"fmt"
)
func main() {
var n, x int
fmt.Scan(&n)
for i := 0; i < n; i++ {
var statement string
fmt.Scan(&statement)
if statement == "++X" || statement == "X++" {
x++
} else if statement == "--X" || statement == "X--" {
x--
}
}
fmt.Println(x)
}
GoRuby:
n = gets.to_i
x = 0
n.times do
statement = gets.chomp
if statement.include?("++")
x += 1
elsif statement.include?("--")
x -= 1
end
end
puts x
RubyRust:
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let n: usize = input.trim().parse().unwrap();
let mut x = 0;
for _ in 0..n {
let mut statement = String::new();
io::stdin().read_line(&mut statement).unwrap();
if statement.contains("++") {
x += 1;
} else if statement.contains("--") {
x -= 1;
}
}
println!("{}", x);
}
RustKotlin:
fun main() {
val n = readLine()!!.toInt()
var x = 0
repeat(n) {
val statement = readLine()!!
if ("++" in statement) {
x++
} else if ("--" in statement) {
x--
}
}
println(x)
}
KotlinExplanation:
- Input Handling: First, read the integer
n
which represents the number of statements. - Logic: For each statement, check if it contains the substring “++” or “–“.
- If it contains “++”, increment
x
by 1. - If it contains “–“, decrement
x
by 1.
- If it contains “++”, increment
- Output: After all statements are processed, print the final value of
x
.