最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - You are given a two-digit integer n. Return the sum of its digits. Example For n = 29, the output should be addTwoD

programmeradmin7浏览0评论

More info:

Input/Output Details:

[time limit] 4000ms (js)

[input] integer n

A positive two-digit integer.

Constraints: 10 ≤ n ≤ 99.

[output] integer

The sum of the first and second digits of the input number.

Below is my attempt

function addTwoDigits(n) {

var num = n;
var n = num.toString();
var sum = n[0] + n[1];
return sum;
}

var userInput= prompt('enter a number');

if (userInput>= 10 && userInput<=99) {

return addTwoDigits(userInput);

} 

console.log(addTwoDigits(n));

More info:

Input/Output Details:

[time limit] 4000ms (js)

[input] integer n

A positive two-digit integer.

Constraints: 10 ≤ n ≤ 99.

[output] integer

The sum of the first and second digits of the input number.

Below is my attempt

function addTwoDigits(n) {

var num = n;
var n = num.toString();
var sum = n[0] + n[1];
return sum;
}

var userInput= prompt('enter a number');

if (userInput>= 10 && userInput<=99) {

return addTwoDigits(userInput);

} 

console.log(addTwoDigits(n));
Share Improve this question edited Jan 13, 2017 at 4:59 RBT 25.9k23 gold badges175 silver badges259 bronze badges asked Jan 13, 2017 at 4:56 monsterreh2bmonsterreh2b 391 gold badge1 silver badge3 bronze badges 2
  • you are adding strings... – epascarello Commented Jan 13, 2017 at 4:59
  • 2 What's your question? – jaybee Commented Jan 13, 2017 at 5:25
Add a ment  | 

12 Answers 12

Reset to default 3

n[0] and n[1] are strings. + is only addition for two numbers, but concatenation for any other case, so "2" + "9" is back at "29" rather than 11 that you hope for. Use parseInt(n[0]) (and similar for n[1]) to turn them into something you can do arithmetic with.

Alternately, you can do this purely numerically, without ever touching strings:

var tens = Math.floor(n / 10);
var ones = n % 10;
var sum = tens + ones;
function addTwoDigits (input){

    var numString = input.toString()
    var numArray = numString.split('')
    var digitOne = []
    var digitTwo = []


    for (var i = 0; i < numArray.length; i++){
      digitOne.push(numArray[0])
      digitTwo.push(numArray[1])
    }
    for (var i = 0; i < digitOne.length; i++){
      digitOne.pop()
    }
    for (var i = 0; i < digitTwo.length; i++){
      digitTwo.pop()
    }

    var numOne = parseInt(digitOne)
    var numTwo = parseInt(digitTwo)
    var sum = numOne + numTwo
    return sum;
}

Here is my answer in Java.

int addTwoDigits(int n) {
  String number = String.valueOf(n);
  int[] nums = new int [number.length()];


  for(int i = 0; i < number.length(); i++){
    nums[i] = Character.getNumericValue(number.charAt(i));
  }

  return nums[0] + nums[1];
}

Use parseInt

function addTwoDigits(n) {

  var num = n;
  var n = num.split("");

  var sum = parseInt(n[0]) + parseInt(n[1]);
  return sum;
}

var userInput = prompt('enter a number');

if (userInput >= 10 && userInput <= 99) {

  console.log(addTwoDigits(userInput));

}

function addTwoDigits(n) {    
    let str = n.toString()
    if (n >= 10 && n < 100){
        return +str[0] + +str[1]
    }
}
function solution(n) {
    let a = Math.floor(n/10);
    let b = n%10;
    return a + b;
}

I used the charAt method and parseInt function to get an answer. You can see it in this code snippet:

function addTwoDigits(n) {
    var string = n.toString();
    var sum = parseInt(string.charAt(0)) + parseInt(string.charAt(1));
    return sum;
}

var userInput = prompt('enter a number');

if (userInput >= 10 && userInput <= 99) {
    console.log(addTwoDigits(userInput));
}

function addDigits(source) {
	return source
	/* convert number to string and split characters to array */
	.toString().split('')
	/* convert char[] to number[] */
	.map(function (elm) { return Number(elm); })
	/* 
	   accumilate all numbers in array to value, which is initally zero. 
	   REF: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Examples
	*/
	.reduce(function (result, current) { return result + current; }, 0)
}

function validate(source) {
	if (typeof(source) == "undefined" || source == null) { throw 'value can not ne NULL ...'; }
	if ((typeof(source) !== 'number')) { throw 'value has to of NUMBER type ....';	}
	if ((source % 1)) { throw 'value has to be an INTEGER ....'; }
	if (!(source >= 10 && source <= 99)) { throw 'value is out of range 10-99 ....'; }
}

/* TESTING ......*/
var samples = [null, 'sdsad', 9.9, 9, 10, 99, 100];
samples.forEach(function (elm) {
	try {
		validate(elm);
		console.log(elm + ': ' + addDigits(elm));
	} catch (exp) {
		console.log(elm + ': ' + exp);
	}
});

<

$(document).ready(function(){

      var $number = $('input[name=number]'),
          $result = $('.result');
      
                                       $('input[name="calculate"]').on('click',function(){
                                     
      var total  = parseInt($number.val()),
          decens = Math.floor(total/10),
          units  = total % 10;
					if (total >9 && total < 100){
          	$result.html(decens + units);
          }
          else {
            $result.html("Total must be an integer between 10 and 99");
          }
        
      });
    });
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>


    <input name="number" />

    <input type="submit" name="calculate" value="Calculate"/>
                                                          
    Result:<span class="result"></span>

Here is a example from me

function solution(n) {
    let num = n;
    let num2 = n.toString().split("");
    let sum = parseInt(num2[0]) + parseInt(num2[1]);
    return sum;
}

Follow,

function solution(n) {
    let num = n.toString().split('')
    return parseInt(num.reduce((acc, cur) => Number(acc) + Number(cur), 0))
}

function solution(n) {
    let num = n.toString().split('')
    return parseInt(num.reduce((acc, cur) => Number(acc) + Number(cur), 0))
}

document.getElementById("input29").innerHTML = solution(29);

document.getElementById("input48").innerHTML = solution(48);
<!DOCTYPE html>
<html>
<body>

<h2>Example</h2>
Input 29: <p id="input29"></p>
<br>
Input 48: <p id="input48"></p>

</body>
</html>

function digit(x) {
  let d1=Math.floor(x/10);
  let d2=x%10;
  let sum=d1+d2;

  return sum;
}

console.log(digit(29));

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论