How to write Kotlin code to store all odd numbers starting at 7 till 101 and print the sum of them?
My code goes like this:
var sum:Int = 0
var num:Int? = null
for(num in 7..101 )
if(num % 2 != 0)
print("$num ")
var result = sum + num
num++
println("$result")
Simply filter the range 7..101 and sum the items:
val total = (7..101).filter { it % 2 == 1 }.sum()
println(total)
Or use sumBy():
val total = (7..101).sumBy { if (it % 2 == 1) it else 0}
println(total)
Or first create a list of all the odd numbers and then get the sum:
val list = (7..101).filter { it % 2 == 1 }
val total = list.sum()
println(total)
If you need to store them, just create a MutableList and add the odd numbers during the forEach execution
var oddNumbersTotal = 0
(7..101).forEach { n ->
if (n % 2 != 0) {
oddNumbersTotal += n
}
}
println(oddNumbersTotal)
You can also try this:
val array = IntArray(48){2*it+1}
print(array.sum())
Related
Hey guys, newbie here. One question, can't understand why this while loop doesn't work even when I entered a int bigger than 9 to the variable num, the while loop should repeat itself until the expression is false, and it doesn't, no output even. Am I missing something here? Thanks in advance.
fun main () {
while(true) {
println ("\nWrite a positive number: ")
var num = readLine()!!.toInt()
var sum = 0
if (num > 9) {
while (num > 9) {
var digit = num % 10
sum = sum + digit
num = num / 10
}
println("\nDigit Sum: $sum")
} else if (num in 1..9) {
println("\nDigit Sum for the number $num is $num")
} else {
println("\nInvalid input, try again.")
}
}
}
The issue is that you are not summing the last num when it gets less or equal to 9. You can even simplify your code a bit. Try the following:
fun main() {
while(true) {
println ("\nWrite a positive number: ")
val insertedNumber = readLine()!!.toInt()
var num = insertedNumber
var sum = 0
while (num > 9) {
val digit = num % 10
sum = sum + digit
num = num / 10
}
sum = sum + num
println("\nDigit Sum for the number $insertedNumber is $sum")
}
}
You don't need to redeclare the variables every time
var sum = sum + digit
var num = num / 10
So simply remove var
sum = sum + digit
num = num / 10
I need to read a sequence of numbers of undefined size & prints the largest number & the position of its first occurrence
Can anyone help with this code:
import java.util.Scanner
fun main() {
val scan = Scanner(System.`in`)
val num = scan.nextInt()
var max = Int.MIN_VALUE
var pos = 0
var i = 1
do {
if (max < num) {
max = num
pos = i
}
i++
} while (scan.hasNext())
print("$max $pos")
}
You just need to read a new number in each iteration:
import java.util.Scanner
fun main() {
val scan = Scanner(System.`in`)
var max = Int.MIN_VALUE
var pos = 0
var i = 1
while (scan.hasNext()) {
// Read a new number here
val num = scan.nextInt()
if (max < num) {
max = num
pos = i
}
i++
}
print("$max $pos")
}
My solution to this task
This is a simple task, it can be solved in a simple way without using a “java.util.Scanner”. You just need to read a new number in each iteration.
fun main() {
var pos = 0
var max = 0
var count = 1
while (true) {
val input = readlnOrNull()
if (input == null) break
val num = input.toInt()
if (pos == 0 || num > max) {
max = num
pos = count
}
count++
}
print("$max $pos")
}
For a given number n, determine whether it contains different digits.
For example, 54 and 323 consist of different digits and 111 and 0 are the same.
you could try this
fun areDigitsDistinct(n:Int) = "$n".toCharArray().distinct().count() > 1
Try this:
fun hasDifferent(number: Int): Boolean {
val stringNumber = number.toString()
if (stringNumber.length == 1) return false
for (char in stringNumber) {
if (char != stringNumber[0]) return true
}
return false
}
Doesn't require convertion to String, doesn't require processing of all digits:
fun sameDigits(number: Int): Boolean {
val veryLastDigit = number % 10
var x = number / 10
while (x > 0) {
val lastDigit = x % 10
if (lastDigit != veryLastDigit) return false
x /= 10
}
return true
}
If you need to make it work with negative numbers too, change part before while-loop to this:
val _number = number.absoluteValue
val veryLastDigit = _number % 10
var x = _number / 10
is there any existing linq function or similiar functions to detect how often values in an ordered list changes from less than zero to greater than zero?
As example, values:
5
2
-2
-5
8 <--- First
6
2
0
1
-3
-5
-3
2 <--- Second
Total count: 2
Sure - it's certainly easy if you're using .NET 4 or higher, using Zip:
// TODO: Consider how you want to handle 0 itself
var count = list.Zip(list.Skip(1), (x, y) => new { x, y })
.Count(pair => pair.x > 0 && pair.y < 0);
That shouldn't be hard to convert into VB if you know VB well :)
Alternatively, if you've really got a list, you can just do it "manually" pretty easily without LINQ:
int count = 0;
for (int i = 0; i < list.Count - 1; i++)
{
if (list[i] > 0 && list[i + 1] < 0)
{
count++;
}
}
You can implement this in one pass using Aggregate:
seq.Aggregate(new { Count=0, LastN = 0}, (state, n) => new {
Count = state.Count + (n > 0 && state.LastN < 0 ? 1 : 0),
LastN = n == 0 ? state.LastN : n
}).Count
This takes into account your wish to include "gradual" transitions such as -1,0,1.
However, a foreach may be easier, simply because it's more conventional. It'll also be faster:
var count = 0;
var lastN = 0;
foreach(var n in seq) {
if(n > 0 && lastN < 0)
count++;
if (n != 0)
lastN = n;
}
How do I add the digits in a particular number for example if the number is 3234 the result should be 3+2+3+4 = 12?
Something along the lines of this should do it:
int val = 3234;
int sum = 0;
while (val != 0) {
sum += (val % 10);
val = val / 10;
}
// Now use sum.
For continued adding until you get a single digit:
int val = 3234;
int sum = val;
while (sum > 9) {
val = sum;
sum = 0;
while (val != 0) {
sum += (val % 10);
val = val / 10;
}
}
// Now use sum.
Note that both of these are destructive to the original val value. If you want to preserve it, you should make a copy or do this in a function so the original is kept.
Hope it is not your homework !
int sum = 0;
while (value!=0) {
sum += value % 10;
value = value / 10;
}