Развернуть число си шарп

How to reverse integers with C# .NET

Say you need to write a function that accepts and integer and returns its reverse. Here come a couple of examples:

Input Output
4 4
28 82
9876 6789
-4 -4
-456 -654
-1928 -8291

So we’re not talking about some mathematical function, but more of a string-reverse. However, note that the negative sign must stay in place, so there’s a little bit of maths in there.

If that doesn’t sound like a problem that you would normally solve in a real life project then you’re probably right. I’m not even sure if there’s a legitimate business use-case for such a function. However, job interview tests often don’t revolve around real-life problems, at least not the initial ones that are meant to filter out candidates that are not a good fit for the position. It’s good to go through the most common problems so that you can breeze through them and have time over for the more difficult ones.

The C# solution is very easy in fact, and I’m sure it’s equally simple in other popular languages. Without any further due here’s one of the many possible solutions out there:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algorithms < public class IntReverse < public int ReverseInteger(int start) < var reverse = string.Join("", Math.Abs(start).ToString().Reverse()); return int.Parse(reverse) * Math.Sign(start); >> >

The above bit takes the incoming integer, takes its absolute value and turns it to a string. Why take the absolute value? We don’t want the ‘-‘ character to end up at the end of the string, so at this point we get rid of it. So at this point we have the following strings:

Читайте также:  Какие бывают типы операторов python
Input Output
4 “4”
28 “28”
9876 “9876”
-4 “4”
-456 “456”
-1928 “1928”

Next we call the Reverse() extension on this string. It returns an IEnumerable , i.e. not the reversed string, but the constituent characters in a reversed order like here:

Input Output
4 [‘4’]
28 [‘8’, ‘2’]
9876 [‘6’, ‘7’, ‘8’, ‘9’]
-4 [‘4’]
-456 [‘6’, ‘5’, ‘4’]
-1928 [‘8’, ‘2’, ‘9’, ‘1’]

The string.Join function takes a delimiter and joins a collection into a string using that delimiter. Since the delimiter is an empty string it means that we don’t want anything in between the joined characters. This is the current state of things at this point:

Input Output
4 “4”
28 “82”
9876 “6789”
-4 “4”
-456 “654”
-1928 “8291”

The values in the Output column are assigned to the reverse variable. It seems we have lost the negative sign on the way, but that’s OK, we can still read it from the incoming start parameter. The Math library has a function called Sign which returns -1 for negative numbers, 0 for 0’s and +1 for positive numbers. So we parse the reverse variable into an integer and multiply it with the correctly signed 1. Hence we have the reversed integer as specified and we can return it.

Here comes a set of unit tests:

using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Algorithms.Tests < [TestClass] public class IntReverseTests < [TestMethod] public void ReverseIntTests() < IntReverse intReverse = new IntReverse(); Assert.AreEqual(4, intReverse.ReverseInteger(4)); Assert.AreEqual(28, intReverse.ReverseInteger(82)); Assert.AreEqual(9876, intReverse.ReverseInteger(6789)); Assert.AreEqual(-4, intReverse.ReverseInteger(-4)); Assert.AreEqual(-456, intReverse.ReverseInteger(-654)); Assert.AreEqual(-1928, intReverse.ReverseInteger(-8291)); >> >

Источник

Развернуть число си шарп

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Reverse Number Program in C#

Reverse a Number and a String in C# with Examples

  1. How to Reverse a Given Number in C#?
  2. How to Reverse a Given String in C#?
How to reverse a given number in C#?

In the following C# program, we take the input number from the console and then reverse that number.

using System; namespace LogicalPrograms < public class Program < static void Main(string[] args) < Console.Write("Enter a Number : "); int number = int.Parse(Console.ReadLine()); int reminder, reverse = 0; while (number >0) < //Get the remainder by dividing the number with 10 reminder = number % 10; //multiply the sum with 10 and then add the reminder reverse = (reverse * 10) + reminder; //Get the quotient by dividing the number with 10 number = number / 10; >Console.WriteLine($"The Reverse order is : "); Console.ReadKey(); > > >
Output:

How to reverse a given number in C#?

How to reverse a string in C#?

In the following C# program, we take the string as an input from the console. Then we reverse the string using for loop.

using System; namespace LogicalPrograms < public class Program < static void Main(string[] args) < Console.Write("Enter a String : "); string name = Console.ReadLine(); string reverse = string.Empty; for (int i = name.Length - 1; i >= 0; i--) < reverse += name[i]; >Console.WriteLine($"The Reverse string is : "); Console.ReadKey(); > > >
Output:

How to reverse a string in C#?

Reverse a string Using Foreach loop in C#:

Let us see how to reverse a string using for each loop in C#.

using System; namespace LogicalPrograms < public class Program < static void Main(string[] args) < Console.Write("Enter a String : "); string name = Console.ReadLine(); string reverse = string.Empty; foreach (char c in name) < reverse = c + reverse; >Console.WriteLine($"The Reverse string is : "); Console.ReadKey(); > > >
Output:

Reverse a string Using Foreach loop in C#:

Reverse a string using Array.Reverse Method in C#:

In the following example, we take a string as an input from the console and then convert that string to a character array. Then we use the Array class Reverse method to reverse the elements of the character array. Once we reverse the elements of the character array, then we create a string from that character array.

using System; namespace LogicalPrograms < public class Program < static void Main(string[] args) < Console.Write("Enter a String : "); string name = Console.ReadLine(); char[] nameArray = name.ToCharArray(); Array.Reverse(nameArray); string reverse = new string(nameArray); Console.WriteLine($"The Reverse string is : "); Console.ReadKey(); > > >
Output:

Reverse a string using Array.Reverse Method in C#

In the next article, I am going to discuss the Armstrong Number Program in C# with some examples. Here, in this article, I try to explain the different ways to Reverse a Number and a String in C# with examples. I hope you enjoy this Reverse a Number and a String in C# article.

Источник

Как перевернуть число?

Пользователь вводит с клавиатуры число, необходимо перевернуть его (число) и вывести на экран.

Примечание: Например, пользователь ввел число 12345. На экране должно появиться число наоборот — 54321.

Как перевернуть число?
Как перевернуть число? Пример: 1210 — 1012

Как перевернуть число?
как перевернуть любое число в Паскале ?

Как перевернуть число
как перевернуть число? например: 0123450=0543210

Как перевернуть натуральное число?
Было 12345 Стало 54321

ИМХО Полученную строку разбиваем на массив символов и выводим этот массив в обратной последовательности

int a = 123; string s = a.ToString(); char[] ar = s.ToCharArray(); Array.Reverse(ar); s = new String(ar); a = Convert.ToInt32(s);

Эксперт по компьютерным сетямЭксперт Pascal/Delphi

const S: string = '12345'; var i: byte; R: string; Begin R:=''; For i:=length(S) downto 1 do R:=R+S[i]; Writeln(R); End.

ЦитатаСообщение от only# Посмотреть сообщение

int a = 123; string s = a.ToString(); char[] ar = s.ToCharArray(); Array.Reverse(ar); s = new String(ar); a = Convert.ToInt32(s);

А вообще желательно что бы использовали числа от 0 до 5 , и можно было написать любое значное число из этих цифр, и он их переворачивал

1 2 3 4 5 6 7 8 9 10 11 12 13
static void Main(string[] args) { Console.WriteLine("Число"); string s = Console.ReadLine(); char[] str = s.ToCharArray();; string a; for (int i = str.Length-1; i > -1; --i) { a = Convert.ToString(str[i]); Console.Write(a); } Console.ReadKey(); }

ЦитатаСообщение от vauper Посмотреть сообщение

А вообще желательно что бы использовали числа от 0 до 5 , и можно было написать любое значное число из этих цифр, и он их переворачивал

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
static void Main(string[] args) { int number, result = 0; Console.Write("enter number: "); number = Int32.Parse(Console.ReadLine()); while (number > 0) { result *= 10; result += number % 10; number /= 10; } Console.WriteLine(result); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
static class IntExt { public static int Reverse(this int i) { int res = 0; while (i != 0) { int remaind; i = Math.DivRem(i, 10, out remaind); res = res * 10 + remaind; } return res; } } int i = 12345.Reverse();

введите 010.
Загадка: это разные числа, или одно число?

00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000010

Источник

C#: Display the number in reverse order

Write a program in C# Sharp to display a number in reverse order.

Pictorial Presentation:

C# Sharp Exercises: Display the number in reverse order

Sample Solution:

C# Sharp Code:

using System; public class Exercise37 < public static void Main() < int num,r,sum=0,t; Console.Write("\n\n"); Console.Write("Display the number in reverse order:\n"); Console.Write("--------------------------------------"); Console.Write("\n\n"); Console.Write("Input a number: "); num = Convert.ToInt32(Console.ReadLine()); for(t=num;t!=0;t=t/10) < r=t % 10; sum=sum*10+r; >Console.Write("The number in reverse order is : \n",sum); > > 
Display the number in reverse order: -------------------------------------- Input a number: 25 The number in reverse order is : 52

Flowchart : Display the number in reverse order

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Оцените статью