Split two digit int - c#

I would like to split a two digit int into 2 one digit ints! For example:
20 = 2 and 0
15 = 1 and 5
8 = 0 and 8

That's easy: use % to get the mod of the number, and / for the integer division (i.e. division where the fractional part is discarded).
Your numbers are in the decimal system (i.e. the base is 10) so you divide and mod by 10, like this:
int a = 20 / 10; // 2
int b = 20 % 10; // 0
To print a number digit-by-digit, least significant digit first, you can use this loop:
int a = 12345;
while (a != 0) {
lastDigit = a % 10;
Console.WriteLine(lastDigit);
a /= 10;
}

int i = 45; // or anything you want
int firstDigit = i / 10;
int secondDigit = i % 10;
It's quite simple really.
You can do this for 3-digit numbers using a Modulos and Division operations as well, but I'll let you figure that out by yourself. ;)

Yeah , easy.
int m =2123;
int n=m;
while (n != 0) {
y=n%10; //variable holds each digit out of the number m.
Console.WriteLine(y);
n /= 10;
}

int input = 15;
int first = 0;
int second = Math.DivRem(input, 10, out first);

If you have a array of integers then you can very well use LINQ, else just use any of the below answers.
int num = 86;
int digit1 = num / 10;
int digit2 = num % 10;
Do your numbers have only two digits?

Related

I'm trying to get sum of digits from a number, Where Is the Mistake? [duplicate]

This question already has answers here:
Sum of digits in C#
(18 answers)
Closed 1 year ago.
int Number = 12;
int Sum = 0;
string sNumber = Convert.ToString(Number);
for(int i = 0; i < sNumber.Length; i++)
{
Sum = Sum + Convert.ToInt32(sNumber[i]);
}
Console.WriteLine(Sum);
it should show 3, But instead its showing 99.
What is actual mistake.
If you iterate the characters in a string, you'll get chars. The problem is that converting a char to an int with Convert.ToInt32(), will result in the ASCII Unicode UTF-16 value of that char.
The ASCII Unicode UTF-16 value of '1' = 49 and for '2' is 50 which sums 99.
You should make it a string first.
int Number = 12;
int Sum = 0;
string sNumber = Convert.ToString(Number);
for(int i = 0; i < sNumber.Length; i++)
{
Sum = Sum + Convert.ToInt32(sNumber[i].ToString());
}
Console.WriteLine(Sum);
The problem is that Convert.ToInt32(sNumber[i]) is getting the numeric value of the character at position i, i.e. Convert.ToInt32('1') gives 49. Note that this value is a char and therefore Convert.ToInt32('1') returns the value of the UTF-16 character.
Why convert it to a string when plain mathematics will do what you want.
int number = 12;
int sum = 0;
while (number > 0){
sum += number % 10;
number /= 10; // Integer division
}
Console.WriteLine(sum);
Convert.ToNumber(char) returns code of character in ASCII. In your example 1 have code 49 and 2 have code 50. 49 + 50 results in 99
You need to use Sum = Sum + int.Parse(sNumber[i].ToString()) to get actual value of digit
no need to convert to string for this. Use simple mathematics.
int Number = 123;
int Sum = 0;
while (Number != 0)
{
Sum += (Number % 10);
Number = Number / 10;
}
System.Console.WriteLine(Sum);
Since it hasn't been posted, here's a simple one-liner using Linq:
int Sum = Number.ToString().Sum(x => (int)char.GetNumericValue(x));
Change it to the following:
int Number = 12;
int Sum = 0;
string sNumber = Convert.ToString(Number);
for (int i = 0; i < sNumber.Length; i++)
{
Sum = Sum + Convert.ToInt32(sNumber.Substring(i,1));
}
Console.WriteLine(Sum);
Use Substring instead of []
Convert.ToInt32(char x) will give you the UTF16 value of the char.
See: https://learn.microsoft.com/de-de/dotnet/api/system.convert.toint32?view=net-5.0#System_Convert_ToInt32_System_Char_

C# For loop index returns ascii instead of current iteration

I need to make a program that calculates the factorial of a number and sums the different numbers.
I'm stuck at the point where I need to take the current number in the for loop to do it's factorial (e.g. the number 145 and I can't take the 5). I've tried the following:
for (int i = length-1; i >= 0; i--)
{
int currentNumber = inputString[i];
currentSum = currentSum * i;
sum += currentSum;
}
inputString is the length of the given number.
The problem is that in this way currentNumber becomes the ascii equivalent (if i = 3 currentSum becomes 51). How do I make currentSum become 3?
Alternatively you could use:
int currentNumber = int.Parse(inputString[i].ToString());
I'd like to suggest an alternative:
int num = int.Parse(inputString); // Convert whole input to int
int sum = 0;
while( num != 0 ) // >0 is not enough, num could be negative.
{
sum += num % 10; // Sum up least significant place
num = num / 10; // "Decimal shift right"
}
With your example "145" this would mean:
Iteration 1:
sum += 145 % 10 => sum = 0 + 5 = 5
num = num / 10 => num = 145 / 10 = 14
Iteration 2:
sum += 14 % 10 => sum = 5 + 4 = 9
num = num / 10 => num = 14 / 10 = 1
Iteration 3:
sum += 1 % 10 => sum = 9 + 1 = 10
num = num / 10 => num = 1 / 10 = 0
num == 0 => end while , sum = 10
Disclaimer: This assumes, the input is in fact a valid integer value. I'd strongly suggest to validate that, first. "Never trust user input."
Assuming inputString is numeric only, you can get away with:
int currentNumber = inputString[i] - '0';
Short explanation: character representation of number '3' is 51, but they are in order (so '0' is 48, '1' is 49, etc.) and you can get the "numerical value" of a character by removing the offset (which is the value of '0').

How to divide number on separate digits to add values to each other

can you help me figure out how to calculate this way, for example I have some integer:
first I need condition
if (x < 10) to avoid asked calculation for single numbers
now if number contains more then 1 digit need to calculate it second way, for example, I got 134 how to separate it to calculate it this way 1 + 3 + 4 to attach this value 8 to variable.
So question is how to separate numbers
try
int num = 12345;
// holder temporarily holds the last digit of the number
int holder = 0;
int sum = 0;
while (num>0)
{
holder = num%10;
num = num/10;
sum += holder;
}
//sum would now hold the sum of each digit
This isn't C# in particular, but you can loop over your number then get it digit by digit.
// -- c
int num = 134;
int sum = 0;
while(num != 0) {
ones_digit = num % 10;
sum += ones_digit;
num = (num - ones_digit) / 10;
}
printf("sum: %d", sum);
On higher-level languages like javascript or python, accessing the digits can also be done by converting the integer to a string, then casting each char to an int type.
// -- javascript
var num = 134;
var digits = num.toString().split("").map(parseInt);
console.log(digits);

How to get the number of elements in an int array?

in this case I want to take the number of elements in the array , but the array is dependent on user input
int first = int.Parse(Console.ReadLine());
int second = int.Parse(Console.ReadLine());
for (int i = first; i <= second; i++)
{
if (i % 5 == 0)
{
int[] some =new int [i];
int c =some.Length;
Console.WriteLine(c);
}
}
I tried several options, but the output is still a list of the numbers divisible by 5 without remainder. How is right to do?
example: first = 15, second = 50.
Expected output = 8.
8 numbers divisible by 5 without remainder(15,20,25,30...50)
You can just loop through the numbers and count how many you find that are divisible by 5:
int first = int.Parse(Console.ReadLine());
int second = int.Parse(Console.ReadLine());
int cnt = 0;
for (int i = first; i <= second; i++) {
if (i % 5 == 0) {
cnt++;
}
}
However, you dont have to generate the numbers to know how many there are. You can just calculate where the last number is (as that is easier than the first) and then calculate how many there are before that but after the first:
int first = int.Parse(Console.ReadLine());
int second = int.Parse(Console.ReadLine());
second -= second % 5;
int cnt = (second - first) / 5 + 1;
For example for the input 3 and 11 you want to count the numbers 5 and 10. The expression 11 % 5 gives 1, so second becomes 10 (the last number). Then second - first is 7, doing integer division with 5 gives 1, and then add 1 gives 2.

Divide X by Y, return number of items in last, partial set

I'm probably missing something really simple, but I'm trying to figure out how to calculate what's left over after I divide X by Y. I don't mean the remainder, I mean, e.g. if I divide 100 by 7 => 6 groups of 15 + one group of 10, how do I get 10?
I don't have code to show because I have no idea where start. X and Y are both integers.
It's not as simple as just using modulus. The fiddly bit is calculating your initial group size from the number of groups.
Try this:
int population = 100;
int numberOfGroups = 7;
int groupSize = (population + numberOfGroups - 1)/numberOfGroups;
Console.WriteLine(groupSize);
int remainder = population%groupSize;
Console.WriteLine(remainder);
I don't mean the remainder
Yes you mean remainder.
If you divide 100 by 15, you get 6 as quotient and 10 as remainder.
use Modulus operator like
int remainder = 100 % 15; // This will return 6
int quotient = 100/15; // This will return 10
It's a modulo operator, isntead of:
var result = x / y;
Try this:
var result = x % y;
EDIT.
Ok You are very unclear but i think one of below solutions is what You are trying to avhieve.
S1. do this:
int x = 100/15;
int z = 15 * x;
int y = 100 - z; // and You got Your 10
S2. do this:
int x = 100/7;
if ( x * 7 != 100)
{
int GroupSize = x+1;
int rest = 100 - GroupSize;
}

Categories