Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace ConsoleApplication12
- {
- class Program
- {
- static void Main(string[] args)
- {
- /*
- We are given an integer number N(read from the console), a
- bit value v(read from the console as well) (v = 0 or 1) and a
- position P(read from the console). Write a sequence of operators
- (a few lines of C# code) that modifies N to hold the value v at the position P
- from the binary representation of N while preserving all other bits in N. Print the resulting
- number on the console.
- */
- long num = long.Parse(Console.ReadLine());
- long pos = long.Parse(Console.ReadLine());
- long bit = long.Parse(Console.ReadLine());
- string binary = Convert.ToString(num, 2);
- char[] binaryChars = new char[64];
- int j = binary.Length - 1;
- int posCount = 0;
- for (long i = binaryChars.Length - 1; i >= 0; i--)
- {
- if (j >= 0)
- {
- binaryChars[i] = binary[j];
- j--;
- }
- else
- {
- binaryChars[i] = '0';
- }
- if (posCount == pos)
- {
- binaryChars[i] = (char)(bit + '0');
- }
- posCount++;
- }
- binary = new string(binaryChars);
- Console.WriteLine(Convert.ToInt64(binary, 2));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement